對(duì)WKWebView中的圖片做緩存

為了對(duì)網(wǎng)頁(yè)中的圖片做緩存加快運(yùn)行速度涧衙,百度到這么一個(gè)抽象類
NSURLProtocol可以監(jiān)聽所有請(qǐng)求日矫。

上代碼档痪,新建一個(gè)NSURLProtocol的分類,

#import <Foundation/Foundation.h>

@interface NSURLProtocol (VCWebView)
+ (void)wk_registerScheme:(NSString*)scheme;
+ (void)wk_unregisterScheme:(NSString*)scheme;
@end
#import "NSURLProtocol+VCWebView.h"
#import <WebKit/WebKit.h>

//FOUNDATION_STATIC_INLINE 屬于屬于runtime范疇探越,你的.m文件需要頻繁調(diào)用一個(gè)函數(shù),可以用static inline來聲明狡赐。從SDWebImage從get到的。
FOUNDATION_STATIC_INLINE Class ContextControllerClass() {
    static Class cls;
    if (!cls) {
        cls = [[[WKWebView new] valueForKey:@"browsingContextController"] class];
    }
    return cls;
}

FOUNDATION_STATIC_INLINE SEL RegisterSchemeSelector() {
    return NSSelectorFromString(@"registerSchemeForCustomProtocol:");
}

FOUNDATION_STATIC_INLINE SEL UnregisterSchemeSelector() {
    return NSSelectorFromString(@"unregisterSchemeForCustomProtocol:");
}

@implementation NSURLProtocol (VCWebView)

+ (void)wk_registerScheme:(NSString *)scheme {
    Class cls = ContextControllerClass();
    SEL sel = RegisterSchemeSelector();
    if ([(id)cls respondsToSelector:sel]) {
        // 放棄編輯器警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [(id)cls performSelector:sel withObject:scheme];
#pragma clang diagnostic pop
    }
}

+ (void)wk_unregisterScheme:(NSString *)scheme {
    Class cls = ContextControllerClass();
    SEL sel = UnregisterSchemeSelector();
    if ([(id)cls respondsToSelector:sel]) {
        // 放棄編輯器警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [(id)cls performSelector:sel withObject:scheme];
#pragma clang diagnostic pop
    }
}
@end

然后創(chuàng)建一個(gè)子類钦幔,繼承NSURLProtocol

#import "VCCustomURLProtocol.h"
#import "SDImageCache.h"
#import "NSData+ImageContentType.h"
#import "UIImage+MultiFormat.h"

static NSString * const hasInitKey = @"VCCustomURLProtocolKey";
@interface VCCustomURLProtocol ()

@property (nonatomic, strong)NSMutableData *responseData;
@property (nonatomic, strong)NSURLConnection *connection;

@end


@implementation VCCustomURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
    if ([request.URL.scheme isEqualToString:@"http"]) {
        NSString *str = request.URL.absoluteString;
        NSString *str1 = request.URL.path;
        NSLog(@"=================================%@",str);
        NSLog(@"=================================%@",str1);
        //只處理http請(qǐng)求的圖片
        if (([str hasSuffix:@".png"] || [str hasSuffix:@".jpg"] || [str hasSuffix:@".gif"])
            && ![NSURLProtocol propertyForKey:hasInitKey inRequest:request]) {
            //yes 表示子類能處理該請(qǐng)求
            NSLog(@"===============yes  yes   yes  yes ");
            return YES;
        }
    }
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    //這邊可用干你想干的事情枕屉。。更改地址鲤氢,提取里面的請(qǐng)求內(nèi)容搀擂,或者設(shè)置里面的請(qǐng)求頭。卷玉。
    return mutableReqeust;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b{
    
    return YES;
}

- (void)startLoading
{
    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
    //做下標(biāo)記哨颂,防止遞歸調(diào)用
    [NSURLProtocol setProperty:@YES forKey:hasInitKey inRequest:mutableReqeust];
    
    //查看本地是否已經(jīng)緩存了圖片
    NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
    
    NSData *data = [[SDImageCache sharedImageCache] diskImageDataBySearchingAllPathsForKey:key];
    
    if (data) {
        NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL
                                                            MIMEType:[NSData sd_contentTypeForImageData:data]
                                               expectedContentLength:data.length
                                                    textEncodingName:nil];
        [self.client URLProtocol:self
              didReceiveResponse:response
              cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        
        [self.client URLProtocol:self didLoadData:data];
        [self.client URLProtocolDidFinishLoading:self];
    }
    else {
        self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];
    }
}

- (void)stopLoading
{
    [self.connection cancel];
}

#pragma mark- NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    [self.client URLProtocol:self didFailWithError:error];
}

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.responseData = [[NSMutableData alloc] init];
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *cacheImage = [UIImage sd_imageWithData:self.responseData];
    //利用SDWebImage提供的緩存進(jìn)行保存圖片
    [[SDImageCache sharedImageCache] storeImage:cacheImage
                           recalculateFromImage:NO
                                      imageData:self.responseData
                                         forKey:[[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]
                                         toDisk:YES];
    
    [self.client URLProtocolDidFinishLoading:self];
}

@end

這樣只要在你加載網(wǎng)頁(yè)的時(shí)候啟動(dòng)或者關(guān)閉監(jiān)聽就好了。

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //注冊(cè)這個(gè)方法相种,用于緩存網(wǎng)頁(yè)的圖片
    [NSURLProtocol registerClass:[VCCustomURLProtocol class]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [NSURLProtocol unregisterClass:[VCCustomURLProtocol class]];
}

這樣就可以實(shí)現(xiàn)了對(duì)網(wǎng)頁(yè)圖片的緩存威恼,大家可以盡情的試試了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蚂子,一起剝皮案震驚了整個(gè)濱河市沃测,隨后出現(xiàn)的幾起案子缭黔,更是在濱河造成了極大的恐慌食茎,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件馏谨,死亡現(xiàn)場(chǎng)離奇詭異别渔,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門哎媚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喇伯,“玉大人,你說我怎么就攤上這事拨与〉揪荩” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵买喧,是天一觀的道長(zhǎng)捻悯。 經(jīng)常有香客問我,道長(zhǎng)淤毛,這世上最難降的妖魔是什么今缚? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮低淡,結(jié)果婚禮上姓言,老公的妹妹穿的比我還像新娘。我一直安慰自己蔗蹋,他們只是感情好何荚,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著猪杭,像睡著了一般兽泣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上胁孙,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天唠倦,我揣著相機(jī)與錄音,去河邊找鬼涮较。 笑死稠鼻,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的狂票。 我是一名探鬼主播候齿,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼闺属!你這毒婦竟也來了慌盯?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤掂器,失蹤者是張志新(化名)和其女友劉穎亚皂,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體国瓮,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡灭必,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年狞谱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片禁漓。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡跟衅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出播歼,到底是詐尸還是另有隱情伶跷,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布秘狞,位于F島的核電站撩穿,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏谒撼。R本人自食惡果不足惜食寡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望廓潜。 院中可真熱鬧抵皱,春花似錦、人聲如沸辩蛋。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)悼院。三九已至伤为,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間据途,已是汗流浹背绞愚。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留颖医,地道東北人位衩。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像熔萧,于是被迫代替她去往敵國(guó)和親糖驴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容