问题
I have the following code:
-(IBAction)downloadButton:(id)sender{
NSURL *url=[NSURL URLWithString:@"http://93.185.34.100/prob/pic1.zip"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadProgressDelegate:progressView];
// NSString *pathString=[NSString stringWithFormat:@"%@/theZip.zip", [[NSBundle mainBundle] resourcePath]];
NSString *filePath = [[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"theZip"] stringByAppendingPathExtension:@"zip"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(@"Directory Contents:\n%@", [fileManager contentsOfDirectoryAtPath:[[NSBundle mainBundle] resourcePath] error:nil ]);
[request setDownloadDestinationPath:filePath];
NSLog(@"Value: %f", [progressView progress]*100);
[request startAsynchronous];
}
It should download and store downloaded zip file into document directory. It does when I run it on simulator but doesn't work on device.
What is the problem?
回答1:
The code you have is getting the path to the bundle directory. Those are the resources that you include with your app. Those resources can be read, but you cannot write or change them, once the app is installed. Essentially, it's a read-only directory for your app.
If you want to save files, you should copy them (or save them) to the app's Documents, Caches, or Application Support folder. You can get the paths to Documents and Caches folders with
NSArray* documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDir = (NSString*)[documentsPaths objectAtIndex:0];
and
NSArray* cachesPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* cachesDir = (NSString*)[cachesPaths objectAtIndex:0];
Here is an Apple reference on saving files in iOS apps (search that page for Determining Where to Save Your App-Specific Files). This will give some info about which directory is most applicable for this kind of data.
The important thing is that you use one of those folders, and not the read-only bundle folder.
来源:https://stackoverflow.com/questions/11602706/save-file-into-application-folder-using-setdownloaddestinationpath