導(dǎo)語
現(xiàn)在NSURLConnection在開發(fā)中會使用的越來越少展氓,iOS9已經(jīng)將NSURLConnection廢棄沙兰,現(xiàn)在最低版本一般適配iOS7北秽,所以也可以使用锄蹂。
NSURLConnection相對于NSURLSession,安全性低畴蹭。NSURLConnection下載有峰值坦仍,比較麻煩處理。
盡管適配最低版本iOS7叨襟,也可以使用NSURLSession繁扎。AFN已經(jīng)不支持NSURLConnection。
NSURLSession:默認(rèn)是掛起狀態(tài)糊闽,如果要請求網(wǎng)絡(luò)梳玫,需要開啟。
[NSURLSession sharedSession] 獲取全局的NSURLSession對象右犹。在iPhone的所有app共用一個全局session. NSURLSessionUploadTask -> NSURLSessionDataTask -> NSURLSessionTask NSURLSessionDownloadTask -> NSURLSessionTask NSURLSessionDownloadTask下載提澎,默認(rèn)下載到tmp文件夾。下載完成后刪除臨時文件念链。所以我們要在刪除文件之前盼忌,將它移動到Cache里。
NSURLSession詳解
NSURLSession基礎(chǔ)
NSURLSession代理
NSURLSession大文件下載
NSURLSession斷點(diǎn)續(xù)傳
1.NSURLSession基礎(chǔ)
第一種網(wǎng)絡(luò)請求方法
//創(chuàng)建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//創(chuàng)建請求
// NSURLRequest * request = [NSURLRequest requestWithURL:url];
//創(chuàng)建Session
NSURLSession * session = [NSURLSession sharedSession];
//創(chuàng)建任務(wù)
NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//開啟網(wǎng)絡(luò)任務(wù)
[task resume];
第二種網(wǎng)絡(luò)請求方法
//創(chuàng)建URL
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
//創(chuàng)建請求
NSURLRequest * request = [NSURLRequest requestWithURL:url];
//創(chuàng)建Session
NSURLSession * session = [NSURLSession sharedSession];
//創(chuàng)建任務(wù)
NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
//開啟網(wǎng)絡(luò)任務(wù)
[task resume];
POST請求
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//設(shè)置請求方法
request.HTTPMethod = @"POST";
//設(shè)置請求體
request.HTTPBody = [@"username=haha&password=123" dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}] resume];
下載文件
NSURL * url = [NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//location 下載到沙盒的地址
NSLog(@"下載完成%@",location);
//response.suggestedFilename 響應(yīng)信息中的資源文件名
NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"緩存地址%@",cachesPath);
//獲取文件管理器
NSFileManager * mgr = [NSFileManager defaultManager];
//將臨時文件移動到緩存目錄下
//[NSURL fileURLWithPath:cachesPath] 將本地路徑轉(zhuǎn)化為URL類型
//URL如果地址不正確掂墓,生成的url對象為空
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
}];
[downloadTask resume];
2.NSURLSession代理
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 全局session
// NSURLSession * session = [NSURLSession sharedSession];
//創(chuàng)建自定義session
//NSURLSessionConfiguration 的 配置
//[[NSOperationQueue alloc] init] 也可以寫成 nil
NSURL * url = [NSURL URLWithString:@"http://192.168.1.200/login.php?username=haha&password=123"];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
NSURLSessionDataTask * task = [session dataTaskWithURL:url];
[task resume];
}
//接收到服務(wù)器響應(yīng)
-
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {NSLog(@"%s",FUNCTION);
//允許接受服務(wù)器回傳數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
//接收服務(wù)器回傳的數(shù)據(jù),有可能執(zhí)行多次
-
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}
//請求成功或失敗
-
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"%@",error);
}
3.NSURLSession大文件下載
import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));
} -
(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[task resume];
}
/*
監(jiān)測臨時文件下載的數(shù)據(jù)大小谦纱,當(dāng)每次寫入臨時文件時,就會調(diào)用一次
bytesWritten 單次寫入多少
totalBytesWritten 已經(jīng)寫入了多少
totalBytesExpectedToWrite 文件總大小
*/
-
(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {//打印下載百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
}
//下載完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager * mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
}
-
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"%@",error);
}
4.NSURLSession斷點(diǎn)續(xù)傳
import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic, strong) NSURLSessionDownloadTask * task;
@property (nonatomic, strong) NSData * resumeData;
@property (nonatomic, strong) NSURLSession * session;
@end
@implementation ViewController
//故事板中開始按鈕的響應(yīng)方法
-
(IBAction)start:(id)sender {
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
self.session = session;
self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.68/丁香花.mp3"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[self.task resume];
}
//故事板中暫停按鈕的響應(yīng)方法
-
(IBAction)pause:(id)sender {
//暫停就是將任務(wù)掛起
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
//保存已下載的數(shù)據(jù)self.resumeData = resumeData;
}];
}
//繼續(xù)按鈕的響應(yīng)方法 -
(IBAction)resume:(id)sender {
//可以使用ResumeData創(chuàng)建任務(wù)
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
//開啟繼續(xù)下載
[self.task resume];
}
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.NSLog(@"%@",NSSearchPathForDirectoriesInDomains(9, 1, 1));
}
/*
監(jiān)測臨時文件下載的數(shù)據(jù)大小梆暮,當(dāng)每次寫入臨時文件時服协,就會調(diào)用一次
bytesWritten 單次寫入多少
totalBytesWritten 已經(jīng)寫入了多少
totalBytesExpectedToWrite 文件總大小
*/
-
(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {//打印下載百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
}
//下載完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager * mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL];
}
-
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"%@",error);
}