美文网首页
UIWebView兼容Webp格式图片

UIWebView兼容Webp格式图片

作者: tljackyi | 来源:发表于2016-11-24 15:39 被阅读151次

    最近项目需要WebView能够兼容Webp格式的图片,节省用户的流量。

    具体实现是通过NSURLProtocol拦截WebView的网络请求,筛选出请求Webp图片的网络请求,下载完Webp图片后使用谷歌的WebP解析库解析图片,转换成Jpg格式图片,传给网页。

    代码如下:

    + (BOOL)canInitWithRequest:(NSURLRequest *)request
    {
        if ([NSURLProtocol propertyForKey:TTWebPProtocolHandledKey inRequest:request]) {
            return NO;
        }
        
        NSURL *url = [request URL];
        NSString *userAgent = [request allHTTPHeaderFields][@"User-Agent"];
        if (![[userAgent lowercaseString] containsString:@"applewebkit"]) {
            return  NO;
        }
        
        NSString* const requestFiletype = [[url pathExtension] lowercaseString];
        
        return [@"webp" isEqualToString:requestFiletype];
    }
    
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
    {
        return request;
    }
    
    - (void)startLoading
    {
        NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
        [NSURLProtocol setProperty:@YES forKey:TTWebPProtocolHandledKey inRequest:mutableReqeust];
    
        self.sessionTask = [self.session dataTaskWithRequest:self.request];
        [self.sessionTask resume];
    }
    
    - (void)stopLoading
    {
        [self.sessionTask cancel];
        self.sessionTask = nil;
    }
    
    
    #pragma mark -- NSURLSessionTaskDelegate
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveResponse:(NSURLResponse *)response
     completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
    {
        self.imgData = [[NSMutableData alloc] init];
        [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        
        if (completionHandler) {
            completionHandler(NSURLSessionResponseAllow);
        }
    }
    
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data
    {
        [self.imgData appendData:data];
    }
    
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
        didCompleteWithError:(nullable NSError *)error
    {
        if (error) {
            [self.client URLProtocol:self didFailWithError:error];
            return;
        }
        
        UIImage *webpImg = [UIImage sd_imageWithData:self.imgData];
        NSData *imgData  = UIImageJPEGRepresentation(webpImg, 1);
        
        [self.client URLProtocol:self didLoadData:imgData];
        [self.client URLProtocolDidFinishLoading:self];
    
    }
    
    #pragma mark -- Setter && Getter
    - (NSURLSession *)session
    {
        if (!_session) {
            
            NSURLSessionConfiguration *sessonConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
            _session = [NSURLSession sessionWithConfiguration:sessonConfig delegate:self delegateQueue:nil];
        }
        return _session;
    }
    
    

    Demo链接

    相关文章

      网友评论

          本文标题:UIWebView兼容Webp格式图片

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