我正在尝试从 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 中。它非常适合模拟器。
最佳答案
没错。
在 iOS 上,应用程序的包是只读的。在 iOS 设备上,任何将更改保存到您的包中的尝试都将失败。
在 Mac OS 上, bundle 不是只读的,但您仍应将其视为只读。修改应用程序的 bundle 不是一个好主意。如果用户从应用商店更新他们的应用,从备份恢复等,那么您保存到 bundle 的更改将会丢失,即使在 Mac OS 上也是如此。
模拟器在 Mac OS 下运行,并针对 Mac OS 框架和 Mac 文件系统构建。
sim 和在设备上运行之间存在很多差异。这是一个。
另一个例子:iOS 文件系统总是区分大小写的。在 Mac OS 上运行的模拟器默认情况下不区分大小写。 (Mac OS 可以从运行不同文件系统的卷中读取。默认文件系统不区分大小写,但您可以将其设置为区分大小写。)
文件“Foo.txt”与文件“foo.txt”是不同的文件。它们可以存在于同一目录中。如果您的文件名为“Foo.txt”并且您尝试使用字符串“foo.txt”加载它,它将在 iOS 设备上失败,但在 Mac OS 上工作。
因此,您应该始终在实际设备上测试您的应用。不要假设如果某些东西在 sim 上正常工作,它对 iOS 设备也是正确的。可能不是。
关于ios - 将图像保存到 Main Bundle 然后将它们加载到 HTML 中可以在模拟器上运行,但不能在真实设备上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30030663/