I have built offline functionality into my UIWebView so that pages that have been loaded are still available when the iPhone is put into airline mode. The basic algorithm is:
1) detect NavigationType LinkClicked and in this case load the requested page from the offline cache;
2) when the offline cache finishes loading the requested URL then it triggers the offlineRequestSuccess notification;
3) my webview handles this notification and loads the response string into the webview.
Here is my code for doing this:
public class UIMobileformsWebView : UIWebView
{
private UIMobileformsWebView () : base()
{
UIWebView self = this;
this.ShouldStartLoad = (webview, request, navigationType) => {
if (navigationType == UIWebViewNavigationType.LinkClicked) {
开发者_开发问答 OfflineRequest.GetInstance().FetchUrl(request.URL);
return false;
}
return true;
};
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("offlineRequestSuccess"), new Action<NSNotification>(OfflineRequestSuccess));
}
void OfflineRequestSuccess (NSNotification notification)
{
ASIHTTPRequest theRequest = (ASIHTTPRequest)notification.Object;
String response = System.IO.File.ReadAllText(theRequest.DownloadDestinationPath);
this.LoadHtmlString(response, theRequest.URL);
}
}
For those that only know Objective C, you can see the same type of mechanism explained in the answer to this question:
Question about UIWebview when tapping links
This basic algorithm works well for most of my webpages, but has an issue with requests made from javascript rather than from clicking a link. If my javascript does window.location.href = URL then the navigation type that I see in the ShouldStartLoad event is type Other, not LinkClicked. Because of this, these requests do not get sent through to my offline cache. The requests coming through from LoadHtmlString also have navigation type of Other, so based on the navigation type I cannot distinguish the requests from LoadHtmlString and javascript requests in my page.
So basically, I am needing to change this line of code:
if (navigationType == UIWebViewNavigationType.LinkClicked) {
to something that beter distinguishes requests coming from my webpages and the request coming from LoadHtmlString in OfflineRequestSuccess. Anyone got any ideas how I could beter make this distinction?
You can easily distinguish these if you set a boolean property of the delegate to true when you use LoadHtmlString and reset it when you finished. The web view is not aware of the property and it won't set it to true. If it the property is YES, it must be because of a LoadHtmlString request.
精彩评论