我正在尝试从 html 字符串中预加载图像标签,以便在设备离线时加载它们。基本上,我从所有<img>
标签中剥离源 url,清理 url 以获得干净的文件名,然后下载图像。
__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];
});
}
然后,在我将 html 字符串加载到 UIWebView 后,它在模拟器上完美运行,但在设备上只是没有加载图像。为什么?
NSURL *baseUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",[[NSBundle mainBundle]bundlePath]]];
[self.webView loadHTMLString:self.htmlPage baseURL:baseUrl];
有什么建议,想法吗?图像在 iOS 设备/模拟器上下载正常,但未在真实设备的 WebView 中加载。它非常适合模拟器。