Radiation hunting
High voltage
Misc
Links
Site news
Urban Exploration

AR Logo

Save image from URL but keep original filename

The Objective C / XCode function below does a really simple thing; It downloads an image from an external URL and then saves it.
The important thing that this function also does is save the image with it's original file name.

Recently i need a function to do this but, although it was easy to find code which downloaded something from a URL, almost all of the pieces of code needed you to supply the new filename.
For my purposes, i had no way of knowing what the file was supposed to be called due to the source link being a gibberish CGI one but it needed to be saved with the correct name.

Eventually i found a really simple solution and i was so pleased that i put it up here in case anyone else needs it.
The key is using the suggestedFilename property of the http response.
The NSURLresponse from the synchronus request is turned in to a NSHTTPURLResponse object and then the property is extracted from that.

The suggested filename is placed in the returning header by the server code so it's not guaranteed but i've found it to be reliable whenever i've used it.


	
- (bool)saveRemoteImage: (NSString*)url_str dest_path:(NSString*)dest_path
{
    NSURLResponse *response;
    NSHTTPURLResponse *httpResponse;
    NSError *error = nil;
    
    NSURL *itemURL = [NSURL URLWithString:url_str];
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:itemURL];
    NSData *imgData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:&response error:nil];
    
    httpResponse = (NSHTTPURLResponse *)response;
    
    if ([[httpResponse suggestedFilename] length] == 0) return FALSE;
    
    NSString *dest_file = [NSString stringWithFormat:@"%@/%@", dest_path, [httpResponse suggestedFilename]];
    
    [imgData writeToFile:dest_file options:0 error:&error];
    
    //NSLog(@"Filename=%@", [httpResponse suggestedFilename]);
    
    if (error) return FALSE;
    else return TRUE;
}