6

I'm trying to download a file from the

-documentPicker:didPickDocumentAtURL:

method. I've tried to get the data of the file using

NSData *data = [NSData dataWithContentsOfURL:url];

but it didn't work how I expected, because the UIDocumentPicker fires the -documentPicker:didPickDocumentAtURL: -method before the file is downloaded.

How can I get the NSData from the file when it's downloaded?

Thanks in advance, Fabian.

FTFT1234
  • 435
  • 8
  • 17

1 Answers1

6

The file actually is downloaded, but you need to use a file coordinator to read the file contents. Something like this should do:

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
    NSError *error = nil;
    [coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSData *data = [NSData dataWithContentsOfURL:newURL];
        // Do something
    }];
    if (error) {
        // Do something else
    }
}
spstanley
  • 940
  • 7
  • 14
  • You don't have to use NSFileCoordinator because this delegate call seems to be synchronous and dataWithContents works perfectly fine. – pronebird Apr 07 '15 at 11:24
  • Well, it wasn't working for him. Plus, I think avoiding NSFileCoordinator leaves too much to chance. Apple says, "All file-related operations must be performed through a file coordinator object." https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/iCloud/iCloud.html – spstanley Apr 08 '15 at 15:17
  • That's right. But with the iOS update to iOS 8.3 the UIDocumentPicker downloads the file showing an activity indicator before dismissing. When the UIDocumentPicker is actually dismissed, I can access the file without the NSFileCoordinator. – FTFT1234 Apr 12 '15 at 12:51
  • Unless it changes while you're accessing it, of course. An iCloud sync can happen at any time. BTW, I did notice the activity indicator, and was very happy to see it. – spstanley Apr 13 '15 at 14:02
  • Can you help with http://stackoverflow.com/questions/30613645/add-edit-in-exel-or-edit-photo-extension – Durgaprasad Jun 08 '15 at 11:07