美文网首页
关于WKWeb加载本地资源

关于WKWeb加载本地资源

作者: 捕梦人 | 来源:发表于2019-01-22 12:14 被阅读0次

提供几种思路 wk要拿本地资源图片举例

  • 第一种 沙盒
    WKWeb通过路径去访问沙盒图片,除了temp可以被访问其他访问不了(尽量用真机去调试),不是很必要的资源可以这么做

  • 第二种 通过拦截协议做替换

// 注入

 [NSURLProtocol registerClass:[WKURLProtocol class]];

 //UIWeb就需上面一句代码 WKweb要使用到如下

    Class cls = NSClassFromString(@"WKBrowsingContextController");
    
    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
    
    if([(id)cls respondsToSelector:sel]) {
#pragma clang diagnostic push
        
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        
        [(id)cls performSelector:sel withObject:@"myapp"];
        
#pragma clang diagnostic pop

//上述调用了私有方法可能悲剧,app开发可以尝试加密拼接运行时等等,去尝试绕开


#import <Foundation/Foundation.h>

@interface WKURLProtocol : NSURLProtocol
{
    NSURLRequest *request;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest;
@end

#import "WKURLProtocol.h"

@implementation WKURLProtocol

//都是重写的系统方法
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest
{
     //判断是否是特定协议,从而进行后面的调用操作
    if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
        return YES;
    }
    return NO;
}

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

- (void)startLoading
{
    //在此方法中做资源替换
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
                                                        MIMEType:@"image/png"
                                           expectedContentLength:-1
                                                textEncodingName:nil];
    
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
    NSData *data = [NSData dataWithContentsOfFile:imagePath];
    
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
    NSLog(@"start loading !");
    
}

- (void)stopLoading
{
    NSLog(@"something went wrong!");
}
@end
  • 第三种 base64 存数据库 或者 文件

  • 第四种 开启一个本地webServer
    gayhub

道阻且长,表面向阳

相关文章

网友评论

      本文标题:关于WKWeb加载本地资源

      本文链接:https://www.haomeiwen.com/subject/udjljqtx.html