【问题标题】:How to use local resources to speed up webview in iOS?如何使用本地资源来加速 iOS 中的 webview?
【发布时间】:2012-10-07 04:05:03
【问题描述】:

我正在将远程网页加载到依赖于 js 和 css 资产的 iOS webview 中。为了提高性能,特别是在 3G 网络上,我希望将这些资产从本地文件调用到 iOS 设备。

支持 iOS 应用的网站也被手机浏览器使用,而不仅仅是 iOS 应用,因此子类化 NSURLRequest 来注册我自己的 URL 前缀 (myurl://) 并不理想。

我已经有代码可以为我的域之外的 URL 启动 mobileSafari:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = [request URL];
    NSString *hostname = [url host];

    if (![hostname hasSuffix:@".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    return YES;
}

这个方法是从同一个控制器实现中调用的,代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    // ...
    webView.delegate = self;

    // ...

        NSURL *url = [[NSURL alloc] initWithString:([path length] > 0 ? path : @"http://mysite.com/mobile/index")];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [webView loadRequest:request];

    // ...

}

我已经查看了其他几个问题(How to use an iPhone webView with an external HTML that references local images?Dynamically loading javascript files in UIWebView with local cache not workingiOS WebView remote html with local image filesUsing local resources in an iPhone webview),但它们似乎都错过了解决我问题的关键要素。

第一个链接的开头很有希望:

if ([url isEqualToString:@"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
    fileToLoad = [[NSBundle mainBundle] pathForResource:@"jquery-1.8.2.min" ofType:@"js"];
}

如果这是一种明智的方法,我会一直纠结于如何将该 fileToLoad NSBundle 传递到 webView 的 loadRequest 中,因为它需要一个 URL。

【问题讨论】:

    标签: ios uiwebview nsurlrequest nsbundle


    【解决方案1】:

    在意识到我可以使用 stringByAppendingPathComponent 的输出作为 URL 之后,我认为我走在了正确的道路上,就像这样......

    if (![hostname hasSuffix:@".mysite.com"] && navigationType == UIWebViewNavigationTypeLinkClicked) {
    
        NSString *urlString = [url absoluteString];
        if ([urlString isEqualToString:@"http://path-to-cdn.com/jquery-1.8.2.min.js"]) {
            NSString *tempurl = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"js/jquery-1.8.2.min.js"];
            [webView loadRequest:[NSMutableURLRequest requestWithURL:tempurl]];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
        return NO;
    }
    return YES;
    

    我还没有让它工作(它仍在加载远程 URL),但我认为我在正确的路径上。

    【讨论】:

    • 我以这个项目为指导在这方面取得了重大进展。 cocoawithlove.com/2010/09/…
    • 好的,cocoawithlove 资源让我能够回答我自己的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2011-11-04
    • 2018-04-26
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多