I’m trying to copy a downloaded file to a specific folder in the app’s documents directory but can’t seem to get it working. The code I’m using is:
NSString *itemPathString = @"http://pathToFolder/folder/myFile.doc";
NSURL *myUrl = [NSURL URLWithString:itemPathString];
NSArray *paths = [fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *folderPath = [[paths objectAtIndex:0] URLByAppendingPathComponent:@"folder"];
NSURL *itemURL = [documentsPath URLByAppendingPathComponent:@"myFile.doc"];
// copy to documents directory asynchronously
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileManager *theFM = [[NSFileManager alloc] init];
NSError *error;
[theFM copyItemAtURL:myUrl toURL:itemURL error:&error];
}
});
I can retrieve the file OK but can’t copy it. Can anyone tell me if there’s anything wrong with the above code?
If downloading a file from a server, if it’s a reasonably small file (e.g. measured in kb, not mb), you can use
dataWithContentsOfURL. You can use that method to load the file into memory, and then use theNSDatainstance methodwriteToFileto save the file.But, if it’s a larger file, you will want to use
NSURLConnection, which doesn’t try to hold the whole file in memory, but rather writes it to the file system when appropriate. The trick here, though, is if you want to download multiple files, you either have to download them sequentially, or encapsulate theNSURLConnectionand theNSOutputStreamsuch that you can have separate copies of those for each simultaneous download.I have uploaded a project, Download Manager that demonstrates what a
NSURLConnectionimplementation might look like, but it’s non-trivial. You might rather want to contemplate using an established, third-party library, such as ASIHTTPRequest or RestKit.