码迷,mamicode.com
首页 > 移动开发 > 详细

IOS-网络(NSURLSession)

时间:2016-02-02 01:18:54      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

 

  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 - NSURLSessionDataTask
112 ///POST请求
113 - (void)sendPostRequest
114 {
115     //1.创建Session对象
116     NSURLSession *session = [NSURLSession sharedSession];
117     
118     //2.创建NSURL
119     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:data
129                                                              options:NSJSONReadingMutableLeaves error:nil];
130         NSLog(@"sendPostRequest:%@",dict);
131     }];
132     //6.开始任务
133     [task resume];
134 }
135 
136 ///GET请求
137 - (void)sendGetRequest
138 {
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:data
146                                                              options:NSJSONReadingMutableLeaves error:nil];
147         NSLog(@"sendGetRequest:%@",dict);
148     }];
149     //3.开始任务
150     [task resume];
151 }
152 @end

 

IOS-网络(NSURLSession)

标签:

原文地址:http://www.cnblogs.com/oc-bowen/p/5176607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!