网络热恋之NSURLSession
生活随笔
收集整理的這篇文章主要介紹了
网络热恋之NSURLSession
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
//
// ViewController.m
// NSURLSession代理簡介 #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; }
//這是為了測試而建立的點擊屏幕事件。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //代理 測試 NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"]; //創(chuàng)建自定義Session NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; NSURLSessionTask * task = [session dataTaskWithURL:url];
//開啟任務(wù)
[task resume]; }
#pragma mark - deleDate
//接受到服務(wù)器響應(yīng)
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
//__FUNCTION__ c語言字符串用s
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 didBecomeInvalidWithError:(NSError *)error{
NSLog(@"%@",error);
}
@end
上面簡單介紹了一下
然后我們來看一個demo
其中下載文件的地址,讀者可以自己配置
//
// ViewController.m
// NSURLSession大文件下載
//
// #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @property (nonatomic, strong) NSURLSessionDownloadTask * task; @property (nonatomic, strong) NSData * resumeData; @property (nonatomic, strong) NSURLSession * session; @end @implementation ViewController - (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.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume];
} - (IBAction)pause:(id)sender { //暫停就是將任務(wù)掛起 [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //保存已下載的數(shù)據(jù)
self.resumeData = resumeData;
}];
} - (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(, , ));
} /* 監(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);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
總結(jié)
以上是生活随笔為你收集整理的网络热恋之NSURLSession的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 力扣168. Excel表列名称
- 下一篇: 农业资源监测站-一款作物整体长势监测的农