Как заархивировать и отправить файл по электронной почте, используя цель c?

Мне нужно сжать мой файл журнала и отправить его по электронной почте. Я использую Objective-zip для архивирования моего файла. И это мой код

-(void)mailLogFile {

    if ([MFMailComposeViewController canSendMail]) {
        NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
        NSString *propertyQuery = [NSString stringWithFormat:@"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
        NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];

        NSLog(@"This is the eNVDS in Recent Activity:%@" ,resultArry);
        [[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:@"This is the eNVDS in Recent Activity:%@" ,resultArry]];
        NSPredicate *notsynced = [NSPredicate predicateWithFormat:@"IsSynced == 0 || IsSynced == %@",@"0"];
        NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
        NSLog(@"This is the eNVDS in Recent Activity which is not synced:%@" ,notsyncedenvds);
        [[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:@"This is the eNVDS in Recent Activity which is not synced:%@" ,notsyncedenvds]];

        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:@"Logfile.txt"];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.zip"];
        NSData *zipdata = [NSData dataWithContentsOfFile:path];
        NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
       //OZZipFile *readFile = [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
        OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
            OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:@"Logfile.txt" compressionLevel:OZZipCompressionLevelBest];

          [stream writeData:data];
          [stream finishedWriting];




        NSString *emailTitle = [NSString stringWithFormat:@"Log file of %@",[NSDate date]];
        NSMutableString *messageBody = [NSMutableString stringWithFormat:@"Login with %@",user[@"Username"]];
        if(![user[@"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:@"\n%@",user[@"PropertyName"]];
        [messageBody appendFormat:@"\nApp version : %@",APP_VERSION];
        [messageBody appendFormat:@"\nPlease describe your problem scenario here."];
        [messageBody appendFormat:@"\n\n\nThanks"];

        NSArray *toRecipents = [NSArray arrayWithObject:@"support@aglive.com"];


        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
        mc.mailComposeDelegate = self;
        [mc setSubject:emailTitle];

        [mc setMessageBody:messageBody isHTML:NO];
        [mc setToRecipients:toRecipents];


        [mc addAttachmentData:zipdata mimeType:@"application/zip" fileName:@"test.zip"];


        [self presentViewController:mc animated:YES completion:nil];

        [zipFile32 close];

    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Aglive Pro" message:@"You have not configured your mail account. Please configure your mail account from the device settings." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
    }
}

прямо сейчас я могу отправить zip-файл по электронной почте, но когда я распаковываю и открываю файл на своем мобильном телефоне или компьютере Mac, я получаю предупреждение о том, что документ "Logfile 4.txt" не может быть открыт. Файл не в правильном формате. Я не знаю, где я иду не так.

1 ответ

Решение

Этот код работал для меня

-(void)mailLogFile {

    if ([MFMailComposeViewController canSendMail]) {
        NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
        NSString *propertyQuery = [NSString stringWithFormat:@"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
        NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];

        NSLog(@"This is the eNVDS in Recent Activity:%@" ,resultArry);
        [[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:@"This is the eNVDS in Recent Activity:%@" ,resultArry]];
        NSPredicate *notsynced = [NSPredicate predicateWithFormat:@"IsSynced == 0 || IsSynced == %@",@"0"];
        NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
        NSLog(@"This is the eNVDS in Recent Activity which is not synced:%@" ,notsyncedenvds);
        [[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:@"This is the eNVDS in Recent Activity which is not synced:%@" ,notsyncedenvds]];

        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:@"Logfile.txt"];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Logfile.zip"];
        NSData *zipdata = [NSData dataWithContentsOfFile:path];

        NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];

        OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
        //NSData *zipdata2 = [NSData dataWithContentsOfFile:zipFile32];
        OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:@"LogFile.txt" compressionLevel:OZZipCompressionLevelBest];

          [stream writeData:data];
          [stream finishedWriting];
[zipFile32 close];
        NSString *emailTitle = [NSString stringWithFormat:@"Log file of %@",[NSDate date]];
        NSMutableString *messageBody = [NSMutableString stringWithFormat:@"Login with %@",user[@"Username"]];
        if(![user[@"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:@"\n%@",user[@"PropertyName"]];
        [messageBody appendFormat:@"\nApp version : %@",APP_VERSION];
        [messageBody appendFormat:@"\nPlease describe your problem scenario here."];
        [messageBody appendFormat:@"\n\n\nThanks"];

        NSArray *toRecipents = [NSArray arrayWithObject:@"support@aglive.com"];


        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
        mc.mailComposeDelegate = self;
        [mc setSubject:emailTitle];

        [mc setMessageBody:messageBody isHTML:NO];
        [mc setToRecipients:toRecipents];
//
        if(zipdata== 0 && zipdata==nil)
        {
            [self mailLogFile];
        }
        else
        {
        [mc addAttachmentData:zipdata mimeType:@"application/zip" fileName:@"Logfile.zip"];



        [self presentViewController:mc animated:YES completion:nil];



       }
Другие вопросы по тегам