swift3.0:NSURLSession的使用

时间:2022-09-28 20:21:22

一、说明

NSURLSession是OC中的会话类,在Swift中变成URLSession类,它们的实现方式是一样的,下面的示例就Swift语法进行讲解和介绍。

二、介绍:

URLSession 类支持3种类型的任务:加载数据、下载和上传。

加载数据:Data Task

下载数据:Downlaod Task

上传数据:Upload Task

毫无疑问,Session Task是整个URLSession架构的核心目标。

三、示例

第1种Data Task用于加载数据。

使用全局share和func dataTask(...)->URLSessionDataTask方法创建。

 //MARK - URLSessionDataTask
func sessionLoadTsk() { //1、创建URL对象;
let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); //2、创建Request对象;
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = URLSession.shared //4、通过创建任务
let dataTask = session.dataTask(with: urlRequest) { (data:Data?, response:URLResponse?, error:Error?) in if(error != nil){
print(error?.localizedDescription);
}else{
//let jsonStr = String(data: data!, encoding:String.Encoding.utf8);
//print(jsonStr)
do {
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print(dic)
} catch let error{
print(error.localizedDescription);
}
}
} as URLSessionDataTask //5、启动任务
dataTask.resume()
}

解析结果:

{
body = (
{
cThumbnail = "http://d.ifengimg.com/w166_h120/p1.ifengimg.com/ifengiclient/ipic/2017040117/swoole_location_1af16fdc4e8301e229769e7892877895_3742809557_size202_w690_h1155.jpg";
cid = 1;
comments = 0;
commentsUrl = "http://share.iclient.ifeng.com/news/sharenews.f?&fromType=spider&aid=301352";
commentsall = 0;
content = "";
ctime = "2017-04-01 18:00:02";
id = "shortNews_301352";
img = (
{
size = {
height = 803;
width = 480;
};
url = "
...........
...........
...........
}

第2种Download Task用于完成下载文件的任务。

如果不需要获取进度,就使用全局的share和func downloadTaskWithRequest(...)->NSURLSessionDownloadTask方法创建。

//MARK - URLSessionDownloadTask
func sessionSimpleDownLoad(){ //1、创建URL下载地址
let url:URL! = URL(string:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491221913316&di=f416fd4642c4b63c8b82521031ce8529&imgtype=0&src=http%3A%2F%2Fimg.tupianzj.com%2Fuploads%2Fallimg%2F160309%2F9-16030Z92137.jpg"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = URLSession.shared //4、通过创建任务
let downLoadTask = session.downloadTask(with: urlRequest) { (location:URL?, response:URLResponse?, error:Error?) in //location位置转换
let locationPath = location?.path //复制到我们自己的目录中
let documentPath:String = "/Users/xiayuanquan/Desktop/demo1.png" //创建文件管理器
let fileManager:FileManager = FileManager.default do{
try fileManager.moveItem(atPath: locationPath!, toPath: documentPath)
}catch let error{
print(error.localizedDescription);
} } as URLSessionDownloadTask //5、启动任务
downLoadTask.resume()
}

下载结果:显示在桌面

swift3.0:NSURLSession的使用

如果需要获取进度,就使用自定义的URLSession和func downloadTaskWithRequest(...)->NSURLSessionDownloadTask方法创建。

1、创建会话单例

//创建一个下载模式--单例实例
public extension DispatchQueue {
private static let _onceToken = NSUUID().uuidString
private static var _onceTracker = [String]()
public class func once(block:()->Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) } if _onceTracker.contains(_onceToken) {
return
}
_onceTracker.append(_onceToken)
block()
}
}

2、执行下载任务

//MARK - URLSessionDownloadTask
func currentSession() -> URLSession {
var currentSession:URLSession?
DispatchQueue.once() {
let config = URLSessionConfiguration.default
currentSession = URLSession(configuration: config, delegate:self, delegateQueue: nil)
}
return currentSession!;
} func sessoinProgressDownload() {
//1、创建URL下载地址
let url:URL! = URL(string:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491221913316&di=f416fd4642c4b63c8b82521031ce8529&imgtype=0&src=http%3A%2F%2Fimg.tupianzj.com%2Fuploads%2Fallimg%2F160309%2F9-16030Z92137.jpg"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = currentSession() //4、下载任务
let downloadTask = session.downloadTask(with: urlRequest) //5、启动任务
downloadTask.resume()
}
}

3、监听代理方法

// MARK -  URLSessionDownloadDelegate
extension URLSessionController:URLSessionDownloadDelegate{ //下载进度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { //获取进度
let written:CGFloat = CGFloat(bytesWritten)
let total:CGFloat = CGFloat(totalBytesWritten)
let pro:CGFloat = written/total
print("----下载进度:------\(pro)");
} //下载偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { //主要用于暂停续传
} //下载结束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { //location位置转换
let locationPath = location.path //复制到我们自己的目录中
let documentPath:String = "/Users/xiayuanquan/Desktop/demo1.png" //创建文件管理器
let fileManager:FileManager = FileManager.default do{
try fileManager.moveItem(atPath: locationPath, toPath: documentPath)
}catch let error{
print(error.localizedDescription);
}
}
}

下载结果:

----下载进度:------1.0
----下载进度:------0.804931929103519
----下载进度:------0.198212299707542
----下载进度:------0.0266228298785133
----下载进度:------0.025989494854822

swift3.0:NSURLSession的使用

第3种Upload Task用于完成上传文件的任务,与下载方法类似。

//使用URLSessionDataTask上传文件
func sessionUpload() { //1、创建URL上传地址,服务器自己搭建
var url:URL! = URL(string:"http://xxx.com/upload.php"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = currentSession() //4、上传数据流
let docmentPath:String = "/Users/xiayuanquan/Desktop/demo1.png";
url = URL.init(string: docmentPath)
do{
let imageData = try Data(contentsOf: url, options: Data.ReadingOptions.alwaysMapped) //5、创建上传任务
let uploadTask = session.uploadTask(with: urlRequest, from: imageData, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
//上传完毕后判断
print("上传完毕")
}) //6、启动任务
uploadTask.resume() }catch let error{
print(error.localizedDescription);
}

四、完整代码

//
// URLSessionController.swift
// NetWorkTest
//
// Created by 夏远全 on 2017/4/3.
// Copyright © 2017年 夏远全. All rights reserved.
// import UIKit class URLSessionController: UIViewController { override func viewDidLoad() {
super.viewDidLoad()
} //第1种Data Task用于加载数据。
//使用全局share和func dataTask(...)->URLSessionDataTask方法创建。
//MARK - URLSessionDataTask
func sessionLoadTsk() { //1、创建URL对象;
let url:URL! = URL(string:"http://api.3g.ifeng.com/clientShortNews?type=beauty"); //2、创建Request对象;
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = URLSession.shared //4、通过创建任务
let dataTask = session.dataTask(with: urlRequest) { (data:Data?, response:URLResponse?, error:Error?) in if(error != nil){
print(error?.localizedDescription);
}else{
//let jsonStr = String(data: data!, encoding:String.Encoding.utf8);
//print(jsonStr)
do {
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print(dic)
} catch let error{
print(error.localizedDescription);
}
}
} as URLSessionDataTask //5、启动任务
dataTask.resume()
} //第2种Download Task用于完成下载文件的任务。
//不需要获取进度,就使用全局的share和func downloadTask(...)->URLSessionDownloadTask方法创建。
//MARK - URLSessionDownloadTask
func sessionSimpleDownLoad(){ //1、创建URL下载地址
let url:URL! = URL(string:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491221913316&di=f416fd4642c4b63c8b82521031ce8529&imgtype=0&src=http%3A%2F%2Fimg.tupianzj.com%2Fuploads%2Fallimg%2F160309%2F9-16030Z92137.jpg"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = URLSession.shared //4、通过创建任务
let downLoadTask = session.downloadTask(with: urlRequest) { (location:URL?, response:URLResponse?, error:Error?) in //location位置转换
let locationPath = location?.path //复制到我们自己的目录中
let documentPath:String = "/Users/xiayuanquan/Desktop/demo1.png" //创建文件管理器
let fileManager:FileManager = FileManager.default do{
try fileManager.moveItem(atPath: locationPath!, toPath: documentPath)
}catch let error{
print(error.localizedDescription);
} } as URLSessionDownloadTask //5、启动任务
downLoadTask.resume()
} //第2种Download Task用于完成下载文件的任务。
//需要获取进度,就使用自定义的URLSession和func downloadTask(with request: URLRequest) -> URLSessionDownloadTask方法创建。
//MARK - URLSessionDownloadTask
func currentSession() -> URLSession {
var currentSession:URLSession?
DispatchQueue.once() {
let config = URLSessionConfiguration.default
currentSession = URLSession(configuration: config, delegate:self, delegateQueue: nil)
}
return currentSession!;
}
func sessoinProgressDownload() {
//1、创建URL下载地址
let url:URL! = URL(string:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491221913316&di=f416fd4642c4b63c8b82521031ce8529&imgtype=0&src=http%3A%2F%2Fimg.tupianzj.com%2Fuploads%2Fallimg%2F160309%2F9-16030Z92137.jpg"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = currentSession() //4、下载任务
let downloadTask = session.downloadTask(with: urlRequest) //5、启动任务
downloadTask.resume()
} //第3种Upload Task用于完成上传文件的任务,与下载方法类似
//使用URLSessionDataTask上传文件
func sessionUpload() { //1、创建URL上传地址
var url:URL! = URL(string:"http://xxx.com/upload.php"); //2、创建Request对象
let urlRequest:URLRequest = URLRequest(url:url); //3、创建会话
let session = currentSession() //4、上传数据流
let docmentPath:String = "/Users/xiayuanquan/Desktop/demo1.png";
url = URL.init(string: docmentPath)
do{
let imageData = try Data(contentsOf: url, options: Data.ReadingOptions.alwaysMapped) //5、创建上传任务
let uploadTask = session.uploadTask(with: urlRequest, from: imageData, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in //上传完毕后判断
print("上传完毕")
}) //6、启动任务
uploadTask.resume() }catch let error{
print(error.localizedDescription);
}
} }
//创建一个下载模式--单例实例
public extension DispatchQueue {
private static let _onceToken = NSUUID().uuidString
private static var _onceTracker = [String]()
public class func once(block:()->Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) } if _onceTracker.contains(_onceToken) {
return
}
_onceTracker.append(_onceToken)
block()
}
} // MARK - URLSessionDownloadDelegate
extension URLSessionController:URLSessionDownloadDelegate{ //下载进度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { //获取进度
let written:CGFloat = CGFloat(bytesWritten)
let total:CGFloat = CGFloat(totalBytesWritten)
let pro:CGFloat = written/total
print("----下载进度:------\(pro)");
} //下载偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { //主要用于暂停续传
} //下载结束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { //location位置转换
let locationPath = location.path //复制到我们自己的目录中
let documentPath:String = "/Users/xiayuanquan/Desktop/demo1.png" //创建文件管理器
let fileManager:FileManager = FileManager.default do{
try fileManager.moveItem(atPath: locationPath, toPath: documentPath)
}catch let error{
print(error.localizedDescription);
}
}
}

swift3.0:NSURLSession的使用的更多相关文章

  1. Swift3.0服务端开发(五) 记事本的开发(iOS端+服务端)

    前边以及陆陆续续的介绍了使用Swift3.0开发的服务端应用程序的Perfect框架.本篇博客就做一个阶段性的总结,做一个完整的实例,其实这个实例在<Swift3.0服务端开发(一)>这篇 ...

  2. Swift3&period;0服务端开发&lpar;一&rpar; 完整示例概述及Perfect环境搭建与配置(服务端&plus;iOS端)

    本篇博客算是一个开头,接下来会持续更新使用Swift3.0开发服务端相关的博客.当然,我们使用目前使用Swift开发服务端较为成熟的框架Perfect来实现.Perfect框架是加拿大一个创业团队开发 ...

  3. 算法与数据结构&lpar;十三&rpar; 冒泡排序、插入排序、希尔排序、选择排序(Swift3&period;0版)

    本篇博客中的代码实现依然采用Swift3.0来实现.在前几篇博客连续的介绍了关于查找的相关内容, 大约包括线性数据结构的顺序查找.折半查找.插值查找.Fibonacci查找,还包括数结构的二叉排序树以 ...

  4. Swift3&period;0变化分享

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  5. swift3&period;0变化总结

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  6. 关于for循环------swift3&period;0

    在程序开发当中,for循环使用的频率无疑是最高的.常用的swift循环是递增式遍历.当然各种循环,swift都能办到.但其大多采用关键字形式实现,大部分开发者更喜欢直接使用C式循环代码.在swift3 ...

  7. Swift2&period;3 --&gt&semi; Swift3&period;0 的变化

    Swift3.0语法变化 首先和大家分享一下学习新语法的技巧: 用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Synt ...

  8. Swift3&period;0都有哪些变化

    从写第一篇Swift文章的时候到现在Swift已经从1.2发展到了今天的3.0,这期间由于Swift目前还在发展阶段并不能向下兼容,因此第一篇文章中的部分代码在当前的Xcode环境中已经无法运行.在W ...

  9. iOS开发 swift3&period;0中文版

    swift3.0中文版: http://pan.baidu.com/s/1nuHqrBb

  10. swift3&period;0的改变

    Swift在这2年的时间内,发展势头迅猛,在它开源后,更是如井喷一样,除了 iOS.mac 平台,还支持了 Linux. 而今年下半年, Swift 3.0 也会随之发布.https://github ...

随机推荐

  1. HTML5 属性 认知

    HTML5中 不支持  Html4.01的属性: <acronym> <applet> <basefont> <big> <center> ...

  2. hadoop删除节点。

    hadoop节点摘除操作: 1.确定exclude文件的位置. <property> <name>dfs.hosts.exclude</name> <valu ...

  3. python 基础——常用日志装饰器

    from functools import wraps class logit(): def __init__(self, logfile='out.log'): self.log = logfile ...

  4. DIV&plus;CSS解决IE6,IE7,IE8,FF兼容问题

    1.IE8下兼容问题,这个最好处理,转化成IE7兼容就可以.在头部加如下一段代码,然后只要在IE7下兼容了,IE8下面也就兼容了:1. <metahttp-equivmetahttp-equiv ...

  5. Github是什么?看完你就了解一些了

    要了解Github,我们首先要知道Git,Git是管理代码的工具,写代码不是件轻松的事儿,一个人写的时候已经不轻松了,一群人写就更不轻松了,但这世界上很多事都是怎么不轻松怎么来的,大部分人都会和别人一 ...

  6. select 训练

    --1.查询"c001"课程比"c002"课程成绩高的所有学生的学号:SELECT b.sno FROM (SELECT * FROM sc WHERE cno ...

  7. WIN7 嵌入式系统安装教程 Windows Embedded Standard 2011 安装

    轻松构建你的第一个 Windows Embedded Standard 2011 镜像.通过本文你可以快速掌握如何使用Windows Embedded Standard 2011 CTP1 来构建一个 ...

  8. MUI之App开发

    一般开发APP分为两种:1.原生ios和android语言开发.2.混合开发,里边穿插h5的东西. 3.第三种:现在因为前端用hbuilder工具开发的情况越来越多,这家公司又提供了更多的选择,所以近 ...

  9. prometheus 配置介绍

    prometheus 配置介绍 prometheus 配置分global.alerting.rule_files.scrape_configs 1.global(全局配置) scrape_interv ...

  10. URL参数编码

    简单明了区分escape.encodeURI和encodeURIComponent 一.前言讲这3个方法区别的文章太多了,但是大部分写的都很绕.本文试图从实践角度去讲这3个方法. 二.escape和它 ...