NSURLSession 簡介
The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of
delegate methods for supporting authentication and gives your app the ability to perform background downloads
when your app is not running or, in iOS, while your app is suspended.
NSURLSession類和相關(guān)類提供一個(gè)API通過HTTP下載內(nèi)容泽腮。這個(gè)API提供了一組豐富的委托方法支持
身份驗(yàn)證和給你的應(yīng)用能力來執(zhí)行后臺(tái)下載局嘁,當(dāng)應(yīng)用程序不運(yùn)行時(shí),或者在iOS應(yīng)用程序被掛起五鲫;
如何創(chuàng)建NSURLSession
/*
* The shared session uses the currently set global NSURLCache,
* NSHTTPCookieStorage and NSURLCredentialStorage objects.
*第一種方式是使用靜態(tài)的sharedSession方法腾啥,該類使用共享的會(huì)話荚恶,該會(huì)話使用全局的Cache长踊,Cookie和證書囱怕。
*/
+ (NSURLSession *)sharedSession;
/*
* Customization of NSURLSession occurs during creation of a new session.
* If you only need to use the convenience routines with custom
* configuration options it is not necessary to specify a delegate.
* If you do specify a delegate, the delegate will be retained until after
* the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
*第二種方式是通過sessionWithConfiguration:方法創(chuàng)建對象霍弹,也就是創(chuàng)
建對應(yīng)配置的會(huì)話,與NSURLSessionConfiguration合作使用娃弓。
*/
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
/*
* 第三種方式是通過sessionWithConfiguration:delegate:delegateQueue方法創(chuàng)建對象典格,二三兩種方式可以創(chuàng)建一個(gè)新會(huì)話并定制其會(huì)話類型。該方式中指定了session的委托和委托所處的隊(duì)列忘闻。當(dāng)不再需要連接時(shí)钝计,可以調(diào)用Session的invalidateAndCancel直接關(guān)閉,或者調(diào)用finishTasksAndInvalidate等待當(dāng)前Task結(jié)束后關(guān)閉齐佳。這時(shí)Delegate會(huì)收到
URLSession:didBecomeInvalidWithError:這個(gè)事件私恬。Delegate收到這個(gè)事件之后會(huì)被解引用。
*/
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue;
NSURLSessionConfiguration
用于配置會(huì)話的屬性炼吴,可以通過該類配置會(huì)話的工作模式
- 有三種模式
+(NSURLSessionConfiguration *)defaultSessionConfiguration;
+(NSURLSessionConfiguration*)ephemeralSessionConfiguration;
+(NSURLSessionConfiguration*)backgroundSessionConfiguration:(NSString *)identifier;
- 幾個(gè)重要屬性
@property BOOL allowsCellularAccess:代表只允許蜂窩數(shù)據(jù)下訪問
@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(NA, 7_0);
discretionary:是根據(jù)系統(tǒng)做性能優(yōu)化本鸣,電量充足的時(shí)候使用wifi
NSURLSessionTask
NSURLSessionTask是一個(gè)抽象子類,它的子類:NSURLSessionDataTask硅蹦,NSURLSessionUploadTask和NSURLSessionDownloadTask荣德;iOS9+的版本新增NSURLSessionStreamTask;
NSURLSessionDataTask的使用
-(void)loadData{
NSURL* url = [NSURL URLWithString:@"http://www.reibang.com"];
NSURLRequest* urlRquest = [NSURLRequest requestWithURL:url];
NSURLSession* urlSession = [NSURLSession sharedSession];
NSURLSessionDataTask* dataTask = [urlSession dataTaskWithRequest:urlRquest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger responseStatusCode = [httpResponse statusCode];
if (responseStatusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString* htmlStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[webView loadHTMLString:htmlStr baseURL:nil];
[self.view addSubview:webView];
});
}
}];
[dataTask resume];
}
NSURLSessionDelegate和NSURLSessionTaskDelegate協(xié)議
在協(xié)議的方法中可以完成各種各樣的回調(diào)動(dòng)作童芹,如身份驗(yàn)證涮瞻、完成任務(wù)后的動(dòng)作、錯(cuò)誤處理和后臺(tái)任務(wù)完成的動(dòng)作等假褪。委托方法指定在NSURLSession中一定數(shù)量的字節(jié)傳輸使用int64_t類型的參數(shù)
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session NS_AVAILABLE_IOS(7_0);
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler NS_AVAILABLE_IOS(7_0);
將任務(wù)切換到后臺(tái)之后署咽,Session的Delegate不會(huì)再收到和Task相關(guān)的消息。當(dāng)所有Task全都完成后,程序?qū)⒈粏拘涯瘢⒄{(diào)用ApplicationDelegate的application:handleEventsForBackgroundURLSession:completionHandler:回調(diào)窒升,在這里要為后臺(tái)session(由background session的identifier標(biāo)識(shí))指定對應(yīng)的回調(diào)代碼塊 隨后,對于每一個(gè)完成的后臺(tái)Task調(diào)用該Session的Delegate中的URLSession:downloadTask:didFinishDownloadingToURL:(成功的話)和URLSession:task:didCompleteWithError:(成功或者失敗都會(huì)調(diào)用)方法做處理慕匠,以上的回調(diào)代碼塊可以在這里調(diào)用
NSURLSessionDownloadTask的使用
NSURL* downLoadURL = [NSURL URLWithString:@"http://pic.4j4j.cn/upload/pic/20131213/0f37a308d8.jpg"];
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:downLoadURL];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDownloadTask* downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSData* data = [NSData dataWithContentsOfURL:location];
UIImage* image = [UIImage imageWithData:data];
self.downLoad_IMageView.image = image;
});
}];
[downLoadTask resume];
NSURLRequest
NSURLRequest及其分類和NSMutableURLRequest及其分類提供了相應(yīng)的API供開發(fā)者配置HTTP請求饱须;類似請求的緩存策略NSURLRequestCachePolicy
、請求超時(shí)時(shí)間timeoutInterval
台谊、設(shè)置請求的Head filed蓉媳、設(shè)置HTTPMethod(GET/POST)、使用POST請求時(shí)設(shè)置HTTPBody等
NSHTTPCookieStorage
對于移動(dòng)端請求服務(wù)器的某些接口時(shí)需要驗(yàn)證這種請求青伤,移動(dòng)端可以使用NSHTTPCookieStorage來獲取服務(wù)端響應(yīng)的Cookie信息督怜,NSHTTPCookieStorage他是一個(gè)單例對象,API中提供了處理Cookie的相關(guān)方法狠角;
NSURLCache
關(guān)于網(wǎng)絡(luò)請求緩存實(shí)現(xiàn)實(shí)現(xiàn)的必要性不言而喻号杠,而實(shí)現(xiàn)方案也是千差萬別;如果對于NSURLCache不了解的話你可能會(huì)走一些彎路丰歌;在NSHipster的NSURLCache這篇文章中詳細(xì)的闡述了NSURLCache能提供的功能姨蟋,在實(shí)際的開發(fā)中你只需要確認(rèn)選取哪種NSURLRequestCachePolicy
即可;
NSURL
對于URL來說他定位了你所發(fā)起請求的地址立帖,在實(shí)際的使用中尤其是GET請求時(shí)眼溶,要注意中文字符的編碼,否則構(gòu)建的請求會(huì)出現(xiàn)問題晓勇;更多的NSURL可以看看這邊文章的介紹堂飞;
NSURLProtocol
對于NSURLProtocol平時(shí)接觸的較少,但NSURLProtocol這篇文件還是給了一些使用建議绑咱;
蘋果的URL Load System
附上蘋果的URL Load System 介紹來加深網(wǎng)絡(luò)請求的理解绰筛。