Search code examples
iphonedownloaddirectorynsdataasihttprequest

Storing NSData in app build-path with ASIHTTPRequest


I am using ASIHTTPRequest to download tiles to be used in my MKMapView. Testing the code it downloads whatever I download into a NSData variable. (My files average 50mb) Note that this is basically almost the same as this unanswered question.

I have found that I can directly download the file from my webserver into a file e.g.:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/Users/ben/Desktop/my_file.txt"];

For mapview I need the files in a folder called Tiles which is inside my app's build. It ends up in this directory:

/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/MyApp.app/Tiles

Which I found out when I called:

NSLog(@"%@",[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Tiles"]);

So what I am trying to do now is download these files (take note the plural) and put them in in the Tiles folder. To start with, I can either ZIP these images together to extract later on my device and place in the Tiles folder, or I can just go ahead and download all the images separately (which seems easier since I already know all the file-names)

I tried this piece of code and it gives me an error. It is in my mapview's viewDidLoad just before I load the tiles. Take note it is only there for testing the download-code and will later be place somewhere else to be triggered by a button.

Here is the code:

NSURL *url = [NSURL URLWithString:@"http://...my-website.../25.png"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Tiles"]]; // THE PROBLEMATIC LINE
[request startSynchronous];
NSError *error = [request error];
if(!error)
{
    NSLog(@"Loaded Map");
}
else
{
    NSLog(@"Error occured while loading map");
    NSLog(@"%@",error);
}

And this appears in the console:

2011-06-26 21:12:09.651 MyApp[5309:707] Error occured while loading map
2011-06-26 21:12:09.669 MyApp[5309:707] Error Domain=ASIHTTPRequestErrorDomain Code=8 "Failed to delete file at path '/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/MyApp.app/Tiles'" UserInfo=0x184b20 {NSUnderlyingError=0x1d4ac0 "The operation couldn’t be completed. (Cocoa error 513.)", NSLocalizedDescription=Failed to delete file at path '/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/MyApp.app/Tiles'}

So how can I store the downloaded file in a directory on the iPhone where I can find and use it later?

Thanks for the trouble.


Solution

  • You can't write directly into your application bundle. You should use a directory inside your app's sandbox, such as /Documents or /Library/Caches. See Getting paths to standard application directories for how to get these paths.