iOS NSURLProtocol的具體使用方法詳解
本文介紹了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功能,在沒有網(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" //在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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
iOS開發(fā)之圖片模糊效果的五種實(shí)現(xiàn)代碼
本篇文章主要介紹了iOS開發(fā)之模糊效果的五種實(shí)現(xiàn)代碼。本文針對(duì)這五種方式講解一下具體的實(shí)現(xiàn),有興趣的同學(xué)可以一起來(lái)了解一下2017-04-04
ios 獲取或修改網(wǎng)頁(yè)上的內(nèi)容
UIWebView是iOS最常用的SDK之一,它有一個(gè)stringByEvaluatingJavaScriptFromString方法可以將javascript嵌入頁(yè)面中,通過(guò)這個(gè)方法我們可以在iOS中與UIWebView中的網(wǎng)頁(yè)元素交互2016-12-12
IOS開發(fā)之由身份證號(hào)碼提取性別的實(shí)現(xiàn)代碼
這篇文章主要介紹了IOS開發(fā)之由身份證號(hào)碼提取性別的實(shí)現(xiàn)代碼的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07
iOS設(shè)置圓角的4種方法實(shí)例(附性能評(píng)測(cè))
這篇文章主要給大家介紹了關(guān)于iOS設(shè)置圓角的4種方法,并給大家附上了性能評(píng)測(cè),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
iOS利用NSAttributedString實(shí)現(xiàn)圖文混排效果示例
iOS7以后,因?yàn)門extKit的強(qiáng)大,可以用NSAttributedString很方便的實(shí)現(xiàn)圖文混排(主要是利用了NSTextAttachment),所以下面這篇文章主要給大家介紹了關(guān)于iOS利用NSAttributedString實(shí)現(xiàn)圖文混排效果的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-10-10
iOS tableView右側(cè)索引視圖狀態(tài)獲取的方法實(shí)例
tableView用于顯示一個(gè)垂直滾動(dòng)的單元格數(shù)(通常為可重復(fù)使用的單元格)組成的視圖,這篇文章主要給大家介紹了關(guān)于iOS tableView右側(cè)索引視圖狀態(tài)獲取的相關(guān)資料,需要的朋友可以參考下2021-07-07

