IOS-網路(NSURLSession)

來源:互聯網
上載者:User

標籤:

 

  1 //  2 //  ViewController.m  3 //  NSURLSession  4 //  5 //  Created by ma c on 16/2/1.  6 //  Copyright © 2016年 博文科技. All rights reserved.  7 //  8   9 #import "ViewController.h" 10  11 @interface ViewController ()<NSURLSessionDownloadDelegate> 12  13 @end 14  15 @implementation ViewController 16 /* 17  任務:任何請求都是一個任務 18   19  NSURLSessionDataTask:普通的GET、POST請求 20  NSURLSessionDownloadTask:檔案下載 21  NSURLSessionUploadTask:檔案上傳 22   23  注意:如果給下載任務設定了completionHandler這個block,也實現了下載代理方法,優先執行block 24  25  */ 26 - (void)viewDidLoad { 27     [super viewDidLoad]; 28      29     self.view.backgroundColor = [UIColor cyanColor]; 30  31 } 32  33 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 34 { 35 //    [self sendGetRequest]; 36 //    [self sendPostRequest]; 37 //    [self downlaodTask1]; 38     [self downlaodTask2]; 39 } 40  41 #pragma mark - NSURLSessionDownloadTask2 42 ///下載任務(有下載進度) 43 - (void)downlaodTask2 44 { 45     //1.建立Session對象 46     NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; 47     NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 48     //2.建立一個任務 49     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; 50     NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url]; 51     //3.開始任務 52     [task resume]; 53 } 54  55 #pragma mark - NSURLSessionDownloadDelegate的代理方法 56 ///下載完畢時調用 57 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 58 { 59     NSLog(@"didFinishDownloadingToURL--->%@",location); 60     //location:檔案的臨時路徑,下載好的檔案 61     NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject]; 62     NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; 63      64     //降臨時檔案夾,剪下或者複製到Caches檔案夾 65     NSFileManager *mgr = [NSFileManager defaultManager]; 66     [mgr moveItemAtPath:location.path toPath:file error:nil]; 67 } 68 ///恢複下載時調用 69 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes 70 { 71      72 } 73 ///每當寫完一部分就調用(根據檔案大小調用多次) 74 //bytesWritten:             這次調用寫了多少 75 //totalBytesWritten:        累計寫了多少長度到沙河中 76 //totalBytesExpectedToWrite:檔案的總長度 77 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite 78 { 79     double progress = (double)totalBytesWritten / totalBytesExpectedToWrite; 80      81     NSLog(@"下載進度--->%lf",progress); 82      83 } 84  85 #pragma mark - NSURLSessionDownloadTask1 86 ///下載任務(不能看到下載進度) 87 - (void)downlaodTask1 88 { 89     //1.建立Session對象 90     NSURLSession *session = [NSURLSession sharedSession]; 91     //2.建立NSURL 92     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; 93     NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { 94        //location:檔案的臨時路徑,下載好的檔案 95         NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject]; 96         NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; 97          98         //降臨時檔案夾,剪下或者複製到Caches檔案夾 99         NSFileManager *mgr = [NSFileManager defaultManager];100         [mgr moveItemAtPath:location.path toPath:file error:nil];101         102         //[mgr copyItemAtPath:location.path toPath:file error:nil];103         104         105     }];106     //3.開始任務107     [task resume];108 }109 110 111 #pragma mark - NSURLSessionDataTask112 ///POST請求113 - (void)sendPostRequest114 {115     //1.建立Session對象116     NSURLSession *session = [NSURLSession sharedSession];117     118     //2.建立NSURL119     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];120     //3.建立請求121     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];122     request.HTTPMethod = @"POST";123     //4.佈建要求體124     request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];125     //5.建立一個任務126     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {127         128         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data129                                                              options:NSJSONReadingMutableLeaves error:nil];130         NSLog(@"sendPostRequest:%@",dict);131     }];132     //6.開始任務133     [task resume];134 }135 136 ///GET請求137 - (void)sendGetRequest138 {139     //1.得到session對象140     NSURLSession *session = [NSURLSession sharedSession];141     //2.建立一個任務142     NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];143     NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {144         145         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data146                                                              options:NSJSONReadingMutableLeaves error:nil];147         NSLog(@"sendGetRequest:%@",dict);148     }];149     //3.開始任務150     [task resume];151 }152 @end

 

IOS-網路(NSURLSession)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.