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

相关文章

JDK21对虚拟线程的几种用法实践指南

《JDK21对虚拟线程的几种用法实践指南》虚拟线程是Java中的一种轻量级线程,由JVM管理,特别适合于I/O密集型任务,:本文主要介绍JDK21对虚拟线程的几种用法,文中通过代码介绍的非常详细,... 目录一、参考官方文档二、什么是虚拟线程三、几种用法1、Thread.ofVirtual().start(

Java8 Collectors.toMap() 的两种用法

《Java8Collectors.toMap()的两种用法》Collectors.toMap():JDK8中提供,用于将Stream流转换为Map,本文给大家介绍Java8Collector... 目录一、简单介绍用法1:根据某一属性,对对象的实例或属性做映射用法2:根据某一属性,对对象集合进行去重二、Du

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

Python中的sort方法、sorted函数与lambda表达式及用法详解

《Python中的sort方法、sorted函数与lambda表达式及用法详解》文章对比了Python中list.sort()与sorted()函数的区别,指出sort()原地排序返回None,sor... 目录1. sort()方法1.1 sort()方法1.2 基本语法和参数A. reverse参数B.

vue监听属性watch的用法及使用场景详解

《vue监听属性watch的用法及使用场景详解》watch是vue中常用的监听器,它主要用于侦听数据的变化,在数据发生变化的时候执行一些操作,:本文主要介绍vue监听属性watch的用法及使用场景... 目录1. 监听属性 watch2. 常规用法3. 监听对象和route变化4. 使用场景附Watch 的

Java Instrumentation从概念到基本用法详解

《JavaInstrumentation从概念到基本用法详解》JavaInstrumentation是java.lang.instrument包提供的API,允许开发者在类被JVM加载时对其进行修改... 目录一、什么是 Java Instrumentation主要用途二、核心概念1. Java Agent

Java 中 Optional 的用法及最佳实践

《Java中Optional的用法及最佳实践》在Java开发中,空指针异常(NullPointerException)是开发者最常遇到的问题之一,本篇文章将详细讲解Optional的用法、常用方... 目录前言1. 什么是 Optional?主要特性:2. Optional 的基本用法2.1 创建 Opti

Python函数的基本用法、返回值特性、全局变量修改及异常处理技巧

《Python函数的基本用法、返回值特性、全局变量修改及异常处理技巧》本文将通过实际代码示例,深入讲解Python函数的基本用法、返回值特性、全局变量修改以及异常处理技巧,感兴趣的朋友跟随小编一起看看... 目录一、python函数定义与调用1.1 基本函数定义1.2 函数调用二、函数返回值详解2.1 有返

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1