2016-03-22 2 views
1

Я создал файл CSV внутри своего приложения с использованием Obj C и привязал его к отправляемому электронному письму. Все это прекрасно работает, и когда вложение файлов открывается с использованием OSX, имя файла читается так, как я ожидаю; "Example.csv".. CSV-файлы, созданные приложением iOS, не читаемые в Windows

Однако, когда я пытаюсь сделать это в Windows, расширение файла больше не отображается и «файл не читается». Когда я изменяю имя файла и добавляю .csv в конце, он становится читаемым.

Почему файл сохраняется после загрузки приложения на компьютер с Windows?

Здесь я определяю «FilePath»;

NSError *error = nil; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/Jobs"]; 
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){ 
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; 
} 
FilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/Jobs/%@.csv",proposalNumber]]; 

Вот код, используемый для генерации CSV-файла;

// Creates a temporary GPS object that we will use to save our database as a .CSV file. 
    GPS *saveGPS = [[GPS alloc] init]; 
    @synchronized(FilePath) { 
     [[NSFileManager defaultManager] createFileAtPath:FilePath contents:nil attributes:nil]; 
     // Creates a file handler which will allow us to write to our file. 
     NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:FilePath]; 
     // Creates and writes the first line to our CSV file, which tells the program reading it what the column titles are. 
     NSString *csvTitleString [email protected]"Source/Receiver, Latitude, Longitude"; 
     [myHandle writeData:[csvTitleString dataUsingEncoding:NSUTF8StringEncoding]]; 
     // Creates initializes another string object which will hold each line we want to write. 
     NSString *csvString = [[NSString alloc] init]; 
     // Declares an array and fills it with all GPS objects found in our Database. 
     NSArray *allGPS = [[NSArray alloc]initWithArray:[database getAllbyProposal:proposalNumber]]; 
     // While the current index value is less than the length of the array write the GPS values into our file then take a new line. 
     for(int i=0;i <= allGPS.count;i++){ 
      if(i < allGPS.count){ 
       saveGPS = [allGPS objectAtIndex:i]; 
       csvString = [NSString stringWithFormat:@"\n %@ %d, %@, %@", [saveGPS sourceReceiver], [[saveGPS positionNo] intValue], [saveGPS latitude], [saveGPS longitude]]; 
       [myHandle seekToEndOfFile]; 
       [myHandle writeData:[csvString dataUsingEncoding:NSUTF8StringEncoding]]; 
      } 
      else if (i == allGPS.count){ 
       @synchronized(FilePath) { 
        // Checks if the device can send email. 
        if([MFMailComposeViewController canSendMail]){ 
         // Sets the subject to data from (our current proposal number). 
         [mail setSubject:[NSString stringWithFormat:@"Data from %@", proposalNumber]]; 
         [mail setMessageBody:@"Please see the attached .CSV file." isHTML:NO]; 
         // Finds the .CSV file we just saved, and attaches it to the email. 
         NSData *myattachment = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@", FilePath]]; 
         [mail addAttachmentData:myattachment mimeType:@"text/csv" fileName:[NSString stringWithFormat:@"%@",proposalNumber]]; 
         // Opens up the email screen. 
         [self presentViewController:mail animated:YES completion:NULL]; 
        } 
        else 
        { 
         // Creates a popup window to inform the user that their email wasn't able to send. 
         UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Error" 
                         message:@"Unable to send email. Have you set up a mail account on this device?" 
                       preferredStyle:UIAlertControllerStyleAlert]; 
         UIAlertAction* dismissAction = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}]; 
         alert.view.tintColor = [UIColor orangeColor]; 
         [alert addAction:dismissAction]; 
         [self presentViewController:alert animated:YES completion:nil]; 
        } 
       } 
      } 
     } 
    } 

ответ

2

В этой строке:

[mail addAttachmentData:myattachment mimeType:@"text/csv" fileName:[NSString stringWithFormat:@"%@",proposalNumber]]; 

вы устанавливаете тип пантомимы, но имя файла не содержит расширения. Mac OS X достаточно умен, чтобы решить, что делать, глядя на тип mime и потенциально содержимое файла. Windows - нет. Windows намного больше зависит от фактического расширения файла.

Добавьте расширение файла к имени файла, поскольку оно прикреплено к электронному письму.

+0

Обратите внимание, что iOS использует соглашение * nix для строк новой строки, то есть заканчивает каждую строку csv LF (подачей строки). Вместо этого Windows ожидает CR LF (возврат каретки, линия). Это может вызвать проблемы при импорте данных позже. – Aaganrmu

+0

Спасибо за помощь, чувствую себя довольно глупо, совершив эту ошибку! –

0

Вы используете расширение ".xls", а не csv. Используйте «.csv» в качестве расширения.

+0

Это ошибка, я опробовал библиотеку xls, чтобы написать .xls вместо .csv, чтобы решить эту проблему и забыл ее вернуть, спасибо за напоминание. –

Смежные вопросы