国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > iOS > 正文

iOS NSURLProtocol的具體使用方法詳解

2020-07-26 02:37:36
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文介紹了iOS NSURLProtocol的具體使用方法詳解,分享給大家,具體如下:

NSURLProtocol定義

這兩天在優(yōu)化項(xiàng)目,無(wú)意間看到了NSURLProtocol,學(xué)習(xí)一下順便總結(jié)下來(lái)。

NSURLProtocol也是蘋果眾多黑魔法中的一種,能夠讓你去重新定義蘋果的URL加載系統(tǒng) (URL Loading System)的行為,URL Loading System里有許多類用于處理URL請(qǐng)求,比如NSURL,NSURLRequest,NSURLConnection和NSURLSession等,當(dāng)URL Loading System使用NSURLRequest去獲取資源的時(shí)候,它會(huì)創(chuàng)建一個(gè)NSURLProtocol子類的實(shí)例,NSURLProtocol看起來(lái)像是一個(gè)協(xié)議,但其實(shí)這是一個(gè)類,而且必須使用該類的子類,并且需要被注冊(cè)。

NSURLProtocol使用范圍

只要是使用NSURLConnection或者 NSURLSession實(shí)現(xiàn)的,你都可以通過(guò)NSURLProtocol做一些自定義的操作。

1、自定義請(qǐng)求和響應(yīng)

2、網(wǎng)絡(luò)的緩存處理(H5離線包 和 網(wǎng)絡(luò)圖片緩存)

3、重定向網(wǎng)絡(luò)請(qǐng)求

4、為測(cè)試提供數(shù)據(jù)Mocking功能,在沒(méi)有網(wǎng)絡(luò)的情況下使用本地?cái)?shù)據(jù)返回。

5、過(guò)濾掉一些非法請(qǐng)求

6、快速進(jìn)行測(cè)試環(huán)境的切換

7、攔截圖片加載請(qǐng)求,轉(zhuǎn)為從本地文件加載

8、可以攔截UIWebView,基于系統(tǒng)的NSURLConnection或者NSURLSession進(jìn)行封裝的網(wǎng)絡(luò)請(qǐng)求。目前WKWebView無(wú)法被NSURLProtocol攔截。

9、當(dāng)有多個(gè)自定義NSURLProtocol注冊(cè)到系統(tǒng)中的話,會(huì)按照他們注冊(cè)的反向順序依次調(diào)用URL加載流程。當(dāng)其中有一個(gè)NSURLProtocol攔截到請(qǐng)求的話,后續(xù)的NSURLProtocol就無(wú)法攔截到該請(qǐng)求。

NSURLProtocol自定義

#import <Foundation/Foundation.h> @interface CustomURLProtocol : NSURLProtocol @end

要實(shí)現(xiàn)下面的方法

+ canInitWithRequest: //抽象方法,子類給出是否能相應(yīng)該請(qǐng)求。如果響應(yīng)YES,說(shuō)明自己的CustomURLProtocol實(shí)現(xiàn)該請(qǐng)求。 + canonicalRequestForRequest://抽象方法,重寫該方法,可以對(duì)請(qǐng)求進(jìn)行修改,例如添加新的頭部信息,修改,修改url等,返回修改后的請(qǐng)求。 + requestIsCacheEquivalent:toRequest://看都是緩存了 - startLoading://開始下載,需要在該方法中發(fā)起一個(gè)請(qǐng)求,對(duì)于NSURLConnection來(lái)說(shuō),就是創(chuàng)建一個(gè)NSURLConnection,對(duì)于NSURLSession,就是發(fā)起一個(gè)NSURLSessionTask 。一般下載前需要設(shè)置該請(qǐng)求正在進(jìn)行下載,防止多次下載的情況發(fā)生 - stopLoading://停止相應(yīng)請(qǐng)求,清空請(qǐng)求Connection 或 Task

使用自定義NSURLProtocol類

1.在單個(gè)的UIViewController中使用

//導(dǎo)入自定義NSURLProtocol類#import "CustomURLProtocol.h"http://在ViewDidLoad中添加攔截網(wǎng)絡(luò)請(qǐng)求的代碼//注冊(cè)網(wǎng)絡(luò)請(qǐng)求攔截[NSURLProtocol registerClass:[CustomURLProtocol class]];//在ViewWillDisappear中添加取消網(wǎng)絡(luò)攔截的代碼//取消注冊(cè)網(wǎng)絡(luò)請(qǐng)求攔截[NSURLProtocol unregisterClass:[CustomURLProtocol class]];

2.攔截整個(gè)App中所有的網(wǎng)絡(luò)請(qǐng)求

//直接在AppDelegate中的didFinishLaunchingWithOptions注冊(cè)網(wǎng)絡(luò)攔截代碼//注冊(cè)Protocol[NSURLProtocol registerClass:[CustomURLProtocol class]];NSURLProtocol使用實(shí)例#define URLProtocolHandledKey @"URLProtocolHandledKey" + (BOOL)canInitWithRequest:(NSURLRequest *)request{ //只處理http和https請(qǐng)求  NSString *scheme = [[request URL] scheme];  if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||   [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame)){    //看看是否已經(jīng)處理過(guò)了,防止無(wú)限循環(huán)    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {      return NO;    }    return YES;  }  return NO;} + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {   /** 可以在此處添加頭等信息 */  NSMutableURLRequest *mutableReqeust = [request mutableCopy];  mutableReqeust = [self redirectHostInRequset:mutableReqeust];  return mutableReqeust;} +(NSMutableURLRequest*)redirectHostInRequset:(NSMutableURLRequest*)request{  if ([request.URL host].length == 0) {    return request;  }   NSString *originUrlString = [request.URL absoluteString];  NSString *originHostString = [request.URL host];  NSRange hostRange = [originUrlString rangeOfString:originHostString];  if (hostRange.location == NSNotFound) {    return request;  }  //定向薄荷喵到主頁(yè)  NSString *ip = @"bohemiao.com";   // 替換域名  NSString *urlString = [originUrlString stringByReplacingCharactersInRange:hostRange withString:ip];  NSURL *url = [NSURL URLWithString:urlString];  request.URL = url;   return request;} + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b{  return [super requestIsCacheEquivalent:a toRequest:b];} - (void)startLoading{  NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];  //標(biāo)示該request已經(jīng)處理過(guò)了,防止無(wú)限循環(huán)  [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];  self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];  //使用NSURLSession也是一樣的} - (void)stopLoading{  [self.connection cancel];} - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {  [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];} - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  [self.client URLProtocol:self didLoadData:data];} - (void) connectionDidFinishLoading:(NSURLConnection *)connection {  [self.client URLProtocolDidFinishLoading:self];} - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {  [self.client URLProtocol:self didFailWithError:error];}

上面用到的一些NSURLProtocolClient方法

@protocol NSURLProtocolClient <NSObject> //請(qǐng)求重定向- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse; // 響應(yīng)緩存是否合法- (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse; //剛接收到Response信息- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy; //數(shù)據(jù)加載成功- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data; //數(shù)據(jù)完成加載- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol; //數(shù)據(jù)加載失敗- (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error; //為指定的請(qǐng)求啟動(dòng)驗(yàn)證- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; //為指定的請(qǐng)求取消驗(yàn)證- (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; @end

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 余庆县| 富蕴县| 嘉禾县| 高平市| 朝阳区| 娄底市| 台中市| 富平县| 宜宾县| 建阳市| 永济市| 英超| 织金县| 阳春市| 鄂伦春自治旗| 晴隆县| 清徐县| 沅陵县| 犍为县| 大姚县| 磐安县| 三门县| 竹溪县| 阜阳市| 灌南县| 绥化市| 平顶山市| 汉源县| 洪湖市| 永清县| 罗城| 武山县| 南康市| 涞水县| 宾川县| 清河县| 延边| 崇文区| 甘肃省| 繁昌县| 青阳县|