iOS邊練邊學--NSURLSession、NSURLSessionTask的介紹與使用以及url中包含了中文的處理方法


一、NSURLSession、NSURLSessionTask的使用步驟

  • 首先創建NSURLSession對象
  • 通過NSURLSession對象創建對應的任務

  <1>NSURLSessionDataTask的GET和POST  -- 以及url中包含了中文的解決辦法

  <2>NSURLSessionDownloadTask實現小文件的下載

  <3>NSURLSessionDownloadTask實現大文件的斷點下載 -- 暫時沒有實現退出程序后的文件續傳

  1 #import "ViewController.h"
  2 // 最好是用到哪個任務就實現哪種任務類型的代理協議
  3 @interface ViewController () <NSURLSessionDownloadDelegate>
  4 @property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
  5 @property (weak, nonatomic) IBOutlet UILabel *precentLabel;
  6 
  7 /** task */
  8 @property(nonatomic,strong) NSURLSessionDownloadTask *task;
  9 
 10 /** resumeData */
 11 @property(nonatomic,strong) NSData *resumeData;
 12 
 13 /** session */
 14 @property(nonatomic,strong) NSURLSession *session;
 15 
 16 @end
 17 
 18 @implementation ViewController
 19 
 20 - (NSURLSession *)session
 21 {
 22     if (_session == nil) {
 23         // 通過設置NSURLSession的Configuration來指定session的代理,以及代理的線程
 24         _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
 25     }
 26     return _session;
 27 }
 28 
 29 - (IBAction)start:(id)sender {
 30     
 31     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]];
 32     // 只通過request創建task  文件的具體下載通過代理來實現,
 33     self.task = [self.session downloadTaskWithRequest:request];
 34     
 35     [self.task resume];
 36     
 37 }
 38 - (IBAction)pause:(id)sender {
 39     // 取消任務 並產生一個恢復數據 -- 任務一旦取消就不能恢復
 40     [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
 41         // 將恢復數據存入變量
 42         self.resumeData = resumeData;
 43     }];
 44     
 45 }
 46 - (IBAction)goOn:(id)sender {
 47     
 48     // 任務已經被取消了,只能重新開啟任務,通過resumeData繼續下載任務
 49     self.task = [self.session downloadTaskWithResumeData:self.resumeData];
 50     
 51     // 恢復任務
 52     [self.task resume];
 53 }
 54 
 55 - (void)viewDidLoad {
 56     [super viewDidLoad];
 57     // Do any additional setup after loading the view, typically from a nib.
 58 }
 59 
 60 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 61     
 62 }
 63 
 64 #pragma mark - <NSURLSessionDownloadDelegate>
 65 
 66 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
 67 {
 68     // bytesWritten -- 本次寫入的長度
 69     // totalBytesWritten -- 目前共寫入的長度
 70     // totalBytesExpectedToWrite -- 期望的長度,也就是總長度
 71     
 72     // 在主線程中修改UI界面
 73     [[NSOperationQueue mainQueue]addOperationWithBlock:^{
 74     
 75     self.progressBar.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
 76     
 77     self.precentLabel.text = [NSString stringWithFormat:@"%0.1f%%",self.progressBar.progress * 100];
 78         
 79     }];
 80     
 81     NSLog(@"%zd / %zd",totalBytesWritten,totalBytesExpectedToWrite);
 82 }
 83 
 84 // 完成下載的時候調用,系統默認將下載的文件存放到了沙盒的temp文件中
 85 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
 86 {
 87     // 剪切文件到Caches
 88     NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
 89     
 90     NSFileManager *mgr = [NSFileManager defaultManager];
 91     
 92     [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
 93     
 94     NSLog(@"didFinishDownloadingToURL");
 95 }
 96 // 任務完成的時候調用
 97 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
 98 {
 99     NSLog(@"didCompleteWithError");
100 }
101 
102 @end
View Code

簡單的界面:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM