【问题标题】:How to distinguish requests coming from LoadHtmlString from webpage requests in event ShouldStartLoad?如何区分来自 LoadHtmlString 的请求和事件 ShouldStartLoad 中的网页请求?
【发布时间】: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


    【解决方案1】:

    如果您在使用 LoadHtmlString 时将代理的布尔属性设置为 true 并在完成时将其重置,则可以轻松区分这些。 Web 视图不知道该属性,并且不会将其设置为 true。如果属性为YES,那一定是因为LoadHtmlString请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-03
      • 2014-06-28
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      相关资源
      最近更新 更多