0

我正在尝试从 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 中加载。它非常适合模拟器。

4

1 回答 1

2

那是对的。

在 iOS 上,App 的包是只读的。在 iOS 设备上,任何将更改保存到捆绑包中的尝试都将失败。

在 Mac OS 上,捆绑包不是只读的,但您仍应将其视为只读。修改应用程序的捆绑包是个坏主意。如果用户从应用商店更新他们的应用,从备份恢复等,那么您保存到捆绑包中的更改将丢失,即使在 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 设备是正确的。可能不是。

于 2015-05-04T13:35:39.627 回答