1 min read

iOS网页离线开发笔记

离线HTML

1.使用Ono解析HTML,将其中的图片、JS保存到本地
2.使用以下方法加载本地的HTML,通过baseURL指定相关资源的路径
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

自定义NSURLProtocol

可以通过继承NSURLProtocol来自定义网络请求
[NSURLProtocol registerClass:[CustomURLProtocol class]];

比如,使WebView中的某类链接显示默认的本地图片

@interface CustomURLProtocol () <NSURLConnectionDelegate>
@end

@implementation CustomURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if (IS_REQUEST_YOU_WANT) {
        return YES;
    }

    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

- (void)startLoading {
    NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"LOCAL_IMAGE"]);
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL
                                                        MIMEType:@"image/png"
                                           expectedContentLength:data.length
                                                textEncodingName:nil];

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)stopLoading {
}

@end