Detecting Download in UIWebView

iphone, objective-c, uiwebview

Solution

You're trying to detect a Content-Type from an NSURLRequest which has not yet been made. You won't know the Content-Type until after the request is made using NSURLConnection. In this case, I'd probably just look at the file extension of the URL path.

Problem

I have a programatically crated `UIWebView`, and it is used to browse a iPhone-style site stored on my server. In this website, there are a few links to files users can download into my application. Right now, I'm trying to detect this with: ``` - (BOOL) webView:(UIWebView *) webView shouldStartLoadWithRequest:(NSURLRequest *) request navigationType:(UIWebViewNavigationType) navigationType { url = [request URL]; NSString *mimeType = [request valueForHTTPHeaderField:@"Content-Type"]; NSLog(@"Content-type: %@", mimeType); if(mimeType == @"application/zip" || mimeType == @"application/x-zip" || mimeType == @"application/octet-stream") { NSLog(@"Downloading file!"); [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"/tmp/file.ipa"]; return NO; } return YES; } ``` However, when this method is called, the content-type header is almost always (null), so I never am able to download a file. How would you do this correctly?

Original source