I'm trying to preload the image tags from an html string in order to load them when the device is offline. Basically, I strip the source url from all the <img>
tags, clean the url to have a clean filename, then download the image.
__block NSString *imageName = [[NSString alloc]init];
//Get the string after HTTP://
NSArray *nohttp = [actualUrl componentsSeparatedByString:@"//"];
imageName = [nohttp objectAtIndex:1];
//Clean any /.:
imageName = [imageName stringByReplacingOccurrencesOfString:@"/" withString:@""];
imageName = [imageName stringByReplacingOccurrencesOfString:@"." withString:@""];
imageName = [imageName stringByReplacingOccurrencesOfString:@":" withString:@""];
//Add .png at the end as we will be saving it as a PNG
imageName = [NSString stringWithFormat:@"%@.png", imageName];
//change the source url to the new filename of the image so the WebView will load it from the main bundle
html = [html stringByReplacingOccurrencesOfString:actualUrl withString:imageName];
//save the image to the main bundle
NSString *pathString = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle]bundlePath], imageName];
//this just checks if the image already exists
BOOL test = [[NSFileManager defaultManager] fileExistsAtPath:pathString];
if (!test){
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:actualUrl]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
NSData *imageData2 = UIImagePNGRepresentation(image);
[imageData2 writeToFile:pathString atomically:YES];
});
}
Then after I load the html string into the UIWebView, it works perfectly on the simulator, but on the device the images just aren't loaded. Why?
NSURL *baseUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",[[NSBundle mainBundle]bundlePath]]];
[self.webView loadHTMLString:self.htmlPage baseURL:baseUrl];
Any suggestions, thoughts? The images download fine on the iOS device/simulator but aren't loaded in the WebView of the real device. It works perfectly for the simulator.