【发布时间】:2011-08-20 08:05:46
【问题描述】:
我在 UIWebView 中内置了离线功能,因此当 iPhone 进入飞行模式时,已加载的页面仍然可用。基本算法是:
1) 检测 NavigationType LinkClicked 并在这种情况下从离线缓存中加载请求的页面;
2) 当离线缓存完成加载请求的 URL 时,它会触发 offlineRequestSuccess 通知;
3) 我的 webview 处理此通知并将响应字符串加载到 webview 中。
这是我的代码:
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);
}
}
对于那些只知道Objective C的人,你可以看到这个问题的答案中解释的相同类型的机制:
Question about UIWebview when tapping links
这个基本算法适用于我的大多数网页,但在使用 javascript 发出的请求而不是点击链接时存在问题。如果我的 javascript 执行 window.location.href = URL 那么我在 ShouldStartLoad 事件中看到的导航类型是 Other 类型,而不是 链接点击。因此,这些请求不会发送到我的离线缓存。来自 LoadHtmlString 的请求也具有 Other 导航类型,因此根据导航类型,我无法区分来自 LoadHtmlString 的请求和页面中的 javascript 请求。
所以基本上,我需要更改这行代码:
if (navigationType == UIWebViewNavigationType.LinkClicked) {
在 OfflineRequestSuccess 中更好地区分来自我的网页的请求和来自 LoadHtmlString 的请求。任何人都知道如何更好地做出这种区分?
【问题讨论】:
标签: objective-c xamarin.ios monodevelop