问题
We are using webarchives in our apps sometimes as it is very convenient way to store HTML + all associated images/CSS/scripts/etc inside a single file on the desktop, put it into the project, and then load it into a UIWebView with a single call like that:
NSData *webArchiveData = /* ... Load data from a single file ... */ ;
[webView
loadData:webArchiveData
MIMEType:@"application/x-webarchive"
textEncodingName:@"utf-8"
baseURL:nil
];
This stopped working on iOS 6 however: the HTML is loaded, but images referenced via relative URLs are not displayed anymore.
回答1:
I traced location.href from a bit of JavaScript within the webarchive and found that on iOS 5 and lower this is the URL of the original HTML that was saved as webarchive. It was serving as a base URL, so relative URLs of resources referenced from the HTML (images, etc.) could be resolved properly and then found within the webarchive (as they are stored there with their original absolute URLs).
On iOS 6 however tracing location.href gives URLs like applewebdata://1B648BC1-F143-4245-A7AD-6424C3E3D227
, so all relative URLs are resolved relative to this one and of course cannot be found in the webarchive anymore.
One of the workarounds I found is to pass something different from nil into loadData:MIMEType:textEncodingName:baseURL:, like this:
[webView
loadData:serializedWebArchive
MIMEType:@"application/x-webarchive"
textEncodingName:@"utf-8"
baseURL:[NSURL URLWithString:@"file:///"] // Passing nil here won't work on iOS 6
];
It works on both iOS 6 and iOS 5 and dumping location.href gives the same absolute URL of the original HTML as before.
Any drawbacks/suggestions?
来源:https://stackoverflow.com/questions/12647267/uiwebview-on-ios-6-does-not-display-images-with-relative-urls-in-webarchives