NSURLSession的应用
2016-01-28 16:46
357 查看
iOS7以后发布了NSURLSession用来替换NSURLConnection,NSURLSession使用方式有以下两种:
1.block方式
(1)创建的步骤
获取单例会话对象
创建URL对象
隐含创建request
创建NSURLSessionDataTask
(2)使用NSURLSessionDataTask
创建session
创建URL
创建URLRequest
创建NSURLSessionDataTask
(3)使用NSURLSessionDownloadTask
// 1.得到session对象
NSURLSession *session = [NSURLSession sharedSession];
// 2.创建URL对象
2.代理方式
(void)downLoadTask2 {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
// 使用配置对象获取会话对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 创建一个URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/test.mp4“];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
[task resume];
}
- (void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager moveItemAtPath:location.path toPath:filePath error:nil];
}
(void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@”已经下载了:%f”, progress);
}
1.block方式
(1)创建的步骤
获取单例会话对象
创建URL对象
隐含创建request
创建NSURLSessionDataTask
// 1.获取会话对象 NSURLSession *session = [NSURLSession sharedSession]; //另外一种生成默认的GET请求的方法 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"]; NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@", dict);
(2)使用NSURLSessionDataTask
创建session
创建URL
创建URLRequest
创建NSURLSessionDataTask
// 2.创建的一URL地址 NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/login"]; // 3.创建一个请求对象 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@", dict); }]; [task resume];
(3)使用NSURLSessionDownloadTask
// 1.得到session对象
NSURLSession *session = [NSURLSession sharedSession];
// 2.创建URL对象
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"]; NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filePath = [caches stringByAppendingPathComponent:response.suggestedFilename]; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager moveItemAtPath:location.path toPath:filePath error:nil]; }];
2.代理方式
(void)downLoadTask2 {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
// 使用配置对象获取会话对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 创建一个URL
NSURL *url = [NSURL URLWithString:@”http://localhost:8080/MJServer/resources/test.mp4“];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
[task resume];
}
- (void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager moveItemAtPath:location.path toPath:filePath error:nil];
}
(void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@”已经下载了:%f”, progress);
}
相关文章推荐
- 取消word的修订模式
- 几种任务调度的 Java 实现方法与比较
- Android特效 五种Toast
- Android中使用Volley开源库进行Http网络请求(GET方式)
- UITextView的基本用法
- Zoho People咨询行业案例
- Python渗透测试工具合集
- 移除IIS默认的响应头
- 在Cordova中自定义AndroidTest(Instrumented Unit Test)
- MYSQL存储过程怎么写
- redis练习手册<二>快速入门
- STL视频_02
- Tomcat在CentOS7下的安装
- C# 字体池技术实现
- iOS---Foundation(NSDecimalNumber.h)
- Android中使用GSON包解析JSON数据(复杂JSON)
- 在Ubuntu上为Android系统内置C可执行程序测试Linux内核驱动程序
- automake示例
- 【树】Sum Root to Leaf Numbers
- the fourth class