日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IOS开发基础之NSURLSession的使用

發布時間:2023/12/18 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IOS开发基础之NSURLSession的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

IOS開發基礎之NSURLSession的使用

服務器我們選用的是tomcat服務器。

所有項目info.plist加入

<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict>

第一章

  • NSURLSession的使用演示之 dataTask 的使用 源碼
// ViewController.m // 25-Session的演示 // Created by 魯軍 on 2021/3/7. #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad {[super viewDidLoad]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[self dataTask3]; } //發送post請求 -(void)dataTask3{NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/login"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"post";NSString *body = @"username=123&pwd=123";request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];NSLog(@"%@",json);}] resume]; } //NSURLSession DataTask //簡化代碼 -(void)dataTask2{NSURL *url = [NSURL URLWithString:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];NSLog(@"%@",json);}] resume]; } -(void)dataTask1{NSURL *url = [NSURL URLWithString:@"http://localhost:8080/DaJunServer/video?method=get&type=JSON"];NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];NSLog(@"%@",json);}];//開始任務[dataTask resume]; } @end

第二章

  • NSURLSession的使用演示之 downloadTask 的使用 下載進度的 源碼
// ViewController.m // 26- 下載進度 // Created by 魯軍 on 2021/3/7. #import "ViewController.h" @interface ViewController () <NSURLSessionDownloadDelegate> @property(nonatomic,strong)NSURLSession *session; @end @implementation ViewController //懶加載 - (NSURLSession *)session{if(_session==nil){NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];_session =[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];}return _session; } - (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view. } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[self downloadTask]; } -(void)downloadTask{NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];//如果設置成代理 不能使用回調。 否則代理的方法不執行 // [[self.session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { // NSLog(@"%@",[NSThread currentThread]); // NSLog(@"--下載完成 : %@",location); // // // }] resume];//在主線程執行的 文件是刪除 的 ,需要的時候。需要自己保存[[self.session downloadTaskWithURL:url] resume]; } //代理方法 //下載完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{NSLog(@"%@",[NSThread currentThread]);NSLog(@"下載完成 %@",location); } //續傳的方法 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{NSLog(@"續傳"); } //獲取進度的方法 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{float process =totalBytesWritten * 1.0 / totalBytesExpectedToWrite;NSLog(@"下載進度 = %f",process); } @end

第三章

  • 斷點續傳的綜合案例的實現
// ViewController.m // 27-斷點續傳 // Created by 魯軍 on 2021/3/7. #import "ViewController.h"@interface ViewController () <NSURLSessionDownloadDelegate> @property(nonatomic,strong)NSURLSession *session; @property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask; @property(nonatomic,strong) NSData *resumeData; @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @end @implementation ViewController //懶加載 - (NSURLSession *)session{if(_session==nil){NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];_session =[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];}return _session; } //開始下載 - (IBAction)startClick:(id)sender {[self download]; } //暫停下載 - (IBAction)pauseClick:(id)sender {[self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {//保存續傳的數據self.resumeData = resumeData;//把續傳數據保存到沙盒容器中NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"456.tmp"];[self.resumeData writeToFile:path atomically:YES];self.downloadTask = nil;NSLog(@"%@",resumeData);}]; }//繼續下載 - (IBAction)resumeClick:(id)sender {//從沙盒容器取文件NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"456.tmp"];NSFileManager *fileManger =[NSFileManager defaultManager];if([fileManger fileExistsAtPath:path]){self.resumeData = [NSData dataWithContentsOfFile:path];}if(self.resumeData == nil){return;}self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];[self.downloadTask resume];self.resumeData = nil; } - (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view. } //開始下載 -(void)download{NSURL *url =[NSURL URLWithString:@"http://localhost:8080/DaJunServer/resources/videos/minion_01.mp4"];NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithURL:url];self.downloadTask = downloadTask;[downloadTask resume]; }//代理方法 //下載完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{NSLog(@"%@",[NSThread currentThread]);NSLog(@"下載完成 %@",location); } //續傳的方法 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{NSLog(@"續傳"); } //獲取進度的方法 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{float process =totalBytesWritten * 1.0 / totalBytesExpectedToWrite;NSLog(@"下載進度 = %f",process);self.progressView.progress = process; } @end

總結

以上是生活随笔為你收集整理的IOS开发基础之NSURLSession的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。