拦截webP的网络请求,利用SDWebImage进行转码,然后加载
//
// WebPLoadProtocol.m
// WCFriend
//
// Created by apple on 2016/11/18.
// Copyright © 2016年 apple. All rights reserved.
//
/*
在需要加载webP的控制器加入此句
[NSURLProtocol registerClass:[WebPLoadProtocol class]];
*/
#import "WebPLoadProtocol.h"
#import "UIImage+WebP.h"
static NSString *URLProtocolHandledKey = @"URLHasHandle";
@interface WebPLoadProtocol ()<NSURLSessionDelegate>
@property(nonatomic, strong) NSURLSession *session;
@end
@implementation WebPLoadProtocol
#pragma mark - 初始化请求
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
//只处理http和https请求
NSString *scheme = [[request URL] scheme];
if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
[scheme caseInsensitiveCompare:@"https"] == NSOrderedSame))
{
if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
return NO;
}
return YES;
}
return NO;
}
+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
#pragma mark - 通信协议内容实现
- (void)startLoading
{
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
//标示改request已经处理过了,防止无限循环
[NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];
if (![[self.request.URL absoluteString] hasSuffix:@"webp"]) {
NSLog(@"是一个正常的,%@",self.request.URL);
}else{
NSLog(@"检测到了 webp---%@,拦截它",self.request.URL);
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue currentQueue]];
[[self.session dataTaskWithRequest:mutableReqeust] resume];
}
- (void)stopLoading
{
[self.session invalidateAndCancel];
}
#pragma mark dataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
if (completionHandler) {
completionHandler(NSURLSessionResponseAllow);
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSData *transData = data;
if ([dataTask.currentRequest.URL.absoluteString hasSuffix:@"webp"]) {
NSLog(@"webp---%@---替换它",dataTask.currentRequest.URL);
//采用 SDWebImage 的转换方法
UIImage *imgData = [UIImage sd_imageWithWebPData:data];
transData = UIImageJPEGRepresentation(imgData, 1.0f);
}
[self.client URLProtocol:self didLoadData:transData];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
if (error) {
[self.client URLProtocol:self didFailWithError:error];
}else{
[self.client URLProtocolDidFinishLoading:self];
}
}
@end