24-NSURLSession的用法

2024-01-13 12:58
文章标签 用法 24 nsurlsession

本文主要是介绍24-NSURLSession的用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

说明:NSURLSession实在IOS7推出的一种新技术,用来代替NSURLConnection.
利用NSURLSession可以更加方便的实现与服务器的交互,更方便的下载上传文件。
NSURLSession的常用方法:

// 常用的类方法
+ (NSURLSession *)sharedSession;
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;// 任务:任何一个请求都是任务
// NSURLSessionDataTask : 普通的GET\POST请求
// NSURLSessionDownloadTask : 文件下载
// NSURLSessionUploadTask : 文件上传
// 下面是常用的创建任务的方法
/* * NSURLSessionTask objects are always created in a suspended state and* must be sent the -resume message before they will execute.*//* Creates a data task with the given request.  The request may have a body stream. */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;/* Creates a data task to retrieve the contents of the given URL. */
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;/* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;/* Creates an upload task with the given request.  The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;/* Creates a download task with the given request. */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;/* Creates a download task to download the contents of the given URL. */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;/* Creates a download task with the resume data.  If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

当需要有下载进度时,需要使用协议,实现NSURLSessionDownloadDelegate方法。

下面是利用NSURLSession实现的下载代码:

//
//  ViewController.m
//  NSURLSession-的使用
//
//  Created by apple on 15-5-20.
//  Copyright (c) 2015年 zzu. All rights reserved.
//#import "ViewController.h"@interface ViewController ()<NSURLSessionDownloadDelegate>@property (nonatomic,strong) NSURLSession *session;@end@implementation ViewController// 任务:任何一个请求都是任务
// NSURLSessionDataTask : 普通的GET\POST请求
// NSURLSessionDownloadTask : 文件下载
// NSURLSessionUploadTask : 文件上传
- (void)viewDidLoad
{[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.
}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    NSLog(@"%@",caches);[self downloadTask2];
}/*** 下载任务:不能看到下载进度*/
- (void)downloadTask
{NSURLSession *session = [NSURLSession sharedSession];NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/images/minion_01.png"];// 创建一个下载taskNSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {// location : 临时文件的路径(下载好的文件)NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];// 将临时文件剪切或复制caches文件NSFileManager *mgr = [NSFileManager defaultManager];[mgr moveItemAtPath:location.path toPath:file error:nil];}];// 开始任务[task resume];
}- (void)downloadTask2
{NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];// 得到session对象NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];// 创建一个下载taskNSURL *url= [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/test.zip"];NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];// 开始任务[task resume];// 如果下载任务设置了completionHandle这个block,也实现了下载的代理方法,则优先执行block
}#pragma mark - <NSURLSessionDownloadDelegate>协议的方法// 下载完毕后调用
// location : 临时文件的路径 (下载好的文件)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];// 将临时文件剪切或复制到caches文件夹NSFileManager *mgr = [NSFileManager defaultManager];[mgr moveItemAtPath:location.path toPath:file error:nil];
}// 恢复下载时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{}//每当下载完一部分数据时,就会调用
// bytesWriten : 本次调用写了多少数据
// totalBytesWritten : 累计写了多少数据到沙盒中
// totalBytesExceptedToWrite : 文件总长度
- (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);
}@end

带断点续传功能的问文件下载:

//
//  ZQViewController.m
//#import "ZQViewController.h"@interface ZQViewController () <NSURLSessionDownloadDelegate, NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
- (IBAction)download:(UIButton *)sender;@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
@end@implementation HMViewController- (NSURLSession *)session
{if (!_session) {// 获得sessionNSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];}return _session;
}- (void)viewDidLoad
{[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (IBAction)download:(UIButton *)sender {// 按钮状态取反sender.selected = !sender.isSelected;if (self.task == nil) { // 开始(继续)下载if (self.resumeData) { // 恢复[self resume];} else { // 开始[self start];}} else { // 暂停[self pause];}
}/***  从零开始*/
- (void)start
{// 1.创建一个下载任务NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"];self.task = [self.session downloadTaskWithURL:url];// 2.开始任务[self.task resume];
}/***  恢复(继续)*/
- (void)resume
{// 传入上次暂停下载返回的数据,就可以恢复下载self.task = [self.session downloadTaskWithResumeData:self.resumeData];// 开始任务[self.task resume];// 清空self.resumeData = nil;
}/***  暂停*/
- (void)pause
{__weak typeof(self) vc = self;[self.task cancelByProducingResumeData:^(NSData *resumeData) {//  resumeData : 包含了继续下载的开始位置\下载的urlvc.resumeData = resumeData;vc.task = nil;}];
}#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];// 将临时文件剪切或者复制Caches文件夹NSFileManager *mgr = [NSFileManager defaultManager];// AtPath : 剪切前的文件路径// ToPath : 剪切后的文件路径[mgr moveItemAtPath:location.path toPath:file error:nil];
}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidWriteData:(int64_t)bytesWrittentotalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{NSLog(@"获得下载进度--%@", [NSThread currentThread]);// 获得下载进度self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{}//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
//{
//
//}
//
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
//{
//
//}
@end

这篇关于24-NSURLSession的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/601532

相关文章

javaSE类和对象进阶用法举例详解

《javaSE类和对象进阶用法举例详解》JavaSE的面向对象编程是软件开发中的基石,它通过类和对象的概念,实现了代码的模块化、可复用性和灵活性,:本文主要介绍javaSE类和对象进阶用法的相关资... 目录前言一、封装1.访问限定符2.包2.1包的概念2.2导入包2.3自定义包2.4常见的包二、stati

Python按照24个实用大方向精选的上千种工具库汇总整理

《Python按照24个实用大方向精选的上千种工具库汇总整理》本文整理了Python生态中近千个库,涵盖数据处理、图像处理、网络开发、Web框架、人工智能、科学计算、GUI工具、测试框架、环境管理等多... 目录1、数据处理文本处理特殊文本处理html/XML 解析文件处理配置文件处理文档相关日志管理日期和

C语言中%zu的用法解读

《C语言中%zu的用法解读》size_t是无符号整数类型,用于表示对象大小或内存操作结果,%zu是C99标准中专为size_t设计的printf占位符,避免因类型不匹配导致错误,使用%u或%d可能引发... 目录size_t 类型与 %zu 占位符%zu 的用途替代占位符的风险兼容性说明其他相关占位符验证示

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

全面解析Golang 中的 Gorilla CORS 中间件正确用法

《全面解析Golang中的GorillaCORS中间件正确用法》Golang中使用gorilla/mux路由器配合rs/cors中间件库可以优雅地解决这个问题,然而,很多人刚开始使用时会遇到配... 目录如何让 golang 中的 Gorilla CORS 中间件正确工作一、基础依赖二、错误用法(很多人一开

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

Java Spring的依赖注入理解及@Autowired用法示例详解

《JavaSpring的依赖注入理解及@Autowired用法示例详解》文章介绍了Spring依赖注入(DI)的概念、三种实现方式(构造器、Setter、字段注入),区分了@Autowired(注入... 目录一、什么是依赖注入(DI)?1. 定义2. 举个例子二、依赖注入的几种方式1. 构造器注入(Con

详解MySQL中JSON数据类型用法及与传统JSON字符串对比

《详解MySQL中JSON数据类型用法及与传统JSON字符串对比》MySQL从5.7版本开始引入了JSON数据类型,专门用于存储JSON格式的数据,本文将为大家简单介绍一下MySQL中JSON数据类型... 目录前言基本用法jsON数据类型 vs 传统JSON字符串1. 存储方式2. 查询方式对比3. 索引

全面掌握 SQL 中的 DATEDIFF函数及用法最佳实践

《全面掌握SQL中的DATEDIFF函数及用法最佳实践》本文解析DATEDIFF在不同数据库中的差异,强调其边界计算原理,探讨应用场景及陷阱,推荐根据需求选择TIMESTAMPDIFF或inte... 目录1. 核心概念:DATEDIFF 究竟在计算什么?2. 主流数据库中的 DATEDIFF 实现2.1

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串