NSURLSession类支持三种类型的任务:加载数据、下载和上传。下面通过样例分别进行介绍。

1,使用Data Task加载数据
使用全局的sharedSession()和dataTaskWithRequest方法创建。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func sessionLoadData(){
    //创建NSURL对象
    let urlString:String="http://hangge.com"
    let url:NSURL! = NSURL(string:urlString)
    //创建请求对象
    let request:NSURLRequest = NSURLRequest(URL: url)
     
    let session = NSURLSession.sharedSession()
   
    let dataTask = session.dataTaskWithRequest(request,
        completionHandler: {(data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
            if error != nil{
                print(error?.code)
                print(error?.description)
            }else{
                let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print(str)
            }
    }) as NSURLSessionTask
     
    //使用resume方法启动任务
    dataTask.resume()  
}

2,使用Download Task来下载文件

(1)不需要获取进度 
使用sharedSession()和downloadTaskWithRequest方法即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func sessionSimpleDownload(){
    //下载地址
    var url = NSURL(string: "http://hangge.com/blog/images/logo.png")
    //请求
    var request:NSURLRequest = NSURLRequest(URL: url!)
     
    let session = NSURLSession.sharedSession()
     
    //下载任务
    var downloadTask = session.downloadTaskWithRequest(request,
        completionHandler: { (location:NSURL!, response:NSURLResponse!, error:NSError!) -> Void in
            //输出下载文件原来的存放目录
            println("location:\(location)")
            //location位置转换
            var locationPath = location.path
            //拷贝到用户目录
            let documnets:String = NSHomeDirectory() + "/Documents/1.png"
            //创建文件管理器
            var fileManager:NSFileManager = NSFileManager.defaultManager()
            fileManager.moveItemAtPath(locationPath!, toPath: documnets, error: nil)
            println("new location:\(documnets)")
    })
     
    //使用resume方法启动任务
    downloadTask.resume()
}

(2)实时获取进度
需要使用自定义的NSURLSession对象和downloadTaskWithRequest方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import UIKit
 
class ViewController: UIViewController ,NSURLSessionDownloadDelegate {
 
    override func viewDidLoad() {
        super.viewDidLoad()
         
        sessionSeniorDownload()
    }
     
    //下载文件
    func sessionSeniorDownload(){
        //下载地址
        var url = NSURL(string: "http://hangge.com/blog/images/logo.png")
        //请求
        var request:NSURLRequest = NSURLRequest(URL: url!)
         
        let session = currentSession() as NSURLSession
         
        //下载任务
        var downloadTask = session.downloadTaskWithRequest(request)
         
        //使用resume方法启动任务
        downloadTask.resume()
    }
     
    //创建一个下载模式
    func currentSession() -> NSURLSession{
        var predicate:dispatch_once_t = 0
        var currentSession:NSURLSession? = nil
        
        dispatch_once(&predicate, {
            var config = NSURLSessionConfiguration.defaultSessionConfiguration()
            currentSession = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
        })
        return currentSession!
    }
     
    //下载代理方法,下载结束
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didFinishDownloadingToURL location: NSURL) {
        //下载结束
        println("下载结束")
         
        //输出下载文件原来的存放目录
        println("location:\(location)")
        //location位置转换
        var locationPath = location.path
        //拷贝到用户目录
        let documnets:String = NSHomeDirectory() + "/Documents/1.png"
        //创建文件管理器
        var fileManager:NSFileManager = NSFileManager.defaultManager()
        fileManager.moveItemAtPath(locationPath!, toPath: documnets, error: nil)
        println("new location:\(documnets)")
    }
     
    //下载代理方法,监听下载进度
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        //获取进度
        var written:CGFloat = (CGFloat)(totalBytesWritten)
        var total:CGFloat = (CGFloat)(totalBytesExpectedToWrite)
        var pro:CGFloat = written/total
        println("下载进度:\(pro)")
    }
     
    //下载代理方法,下载偏移
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        //下载偏移,主要用于暂停续传
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

3,使用Upload Task来上传文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func sessionUpload(){
    //上传地址
    var url = NSURL(string: "http://hangge.com/")
    //请求
    var request:NSURLRequest = NSURLRequest(URL: url!)
     
    let session = NSURLSession.sharedSession()
     
    //上传数据流
    let documents =  NSHomeDirectory() + "/Documents/1.png"
    var imgData = NSData(contentsOfFile: documents)
     
    var uploadTask = session.uploadTaskWithRequest(request, fromData: imgData) {
        (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
        //上传完毕后
        println("上传完毕")
    }
     
    //使用resume方法启动任务
    uploadTask.resume()
}

Swift - 使用NSURLSession加载数据、下载、上传文件的更多相关文章

  1. iOS开发——网络Swift篇&NSURLSession加载数据、下载、上传文件

    NSURLSession加载数据.下载.上传文件   NSURLSession类支持三种类型的任务:加载数据.下载和上传.下面通过样例分别进行介绍.   1,使用Data Task加载数据 使用全局的 ...

  2. https 协议下服务器根据网络地址下载上传文件问题

    https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题) 使用h ...

  3. git下载/上传文件提示:git did not exit cleanly

    问题:git操作下载/上传文件,提示信息如下 TortoiseGit-git did not exit cleanly (exit code 1) TortoiseGit-git did not ex ...

  4. Android 利用an框架快速实现网络请求(含下载上传文件)

    作者:Bgwan链接:https://zhuanlan.zhihu.com/p/22573081来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. an框架的网络框架是完全 ...

  5. $Django ajax简介 ajax简单数据交互,上传文件(form-data格式数据),Json数据格式交互

    一.ajax  1 什么是ajax:异步的JavaScript和xml,跟后台交互,都用json  2 ajax干啥用的?前后端做数据交互:  3 之前学的跟后台做交互的方式:   -第一种:在浏览器 ...

  6. 前台提交数据(表单数据、Json数据及上传文件)的类型

    MIME (Multipurpose Internet Mail Extensions) 是描述内容类型的互联网标准.Clients use this content type or media ty ...

  7. 从Linux服务器下载上传文件

    首先要确定好哪两种的连接:Linux常用的有centors和unbantu两种版本,PC端Mac和Windows 如果在两个Linux之间传输,或Linux和Mac之间传输可以使用scp命令,类似于s ...

  8. 亚马逊S3下载上传文件

    引用网址: http://www.jxtobo.com/27697.html 下载 CloudBerry Explorer http://www.cloudberrylab.com/download- ...

  9. java Socket Tcp示例三则(服务端处理数据、上传文件)

    示例一: package cn.itcast.net.p5.tcptest; import java.io.BufferedReader;import java.io.IOException;impo ...

随机推荐

  1. BZOJ 1324: Exca王者之剑

    1324: Exca王者之剑 Description Input 第一行给出数字N,M代表行列数.N,M均小于等于100 下面N行M列用于描述数字矩阵 Output 输出最多可以拿到多少块宝石 Sam ...

  2. Windows 下统计行数的命令

    大家都知道在Linux下统计文本行数能够用wc -l 命令.比如: -bash-3.2$ cat pif_install.log | wc -l       712 但在Windows下怎样统计输出文 ...

  3. JavaScript 高级程序设计(第3版)笔记——chapter5:引用类型

    Chapter5 引用类型 本章内容: l  使用对象 l  创建并操作数组 l  理解基本的JavaScript类型 l  使用基本类型和基本包装类型 l  从技术上讲,JavaScript是一门面 ...

  4. javaku快捷键

    Eclipse 的编辑功能非常强大,掌握了 Eclipse 快捷键功能,能够大大提高开发效率.Eclipse 中有如下一些和编辑相关的快捷键. 1. [ALT+/] 此快捷键为用户编辑的好帮手,能为用 ...

  5. Servlet中通过过滤器实现统一的手动编码(解决中文乱码)

    1.web.xml片段: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi= ...

  6. C++创建动态链接库(*.dll)

    1.      从 “文件”菜单中,选择 “新建”,然后选择 “项目…”. 2.      在“项目类型”窗格中,选择“Visual C++”下的“Win32”. 3.      在“模板”窗格中,选 ...

  7. C++编译时函数名修饰约定规则(很具体),MFC提供的宏,extern "C"的作用

    调用约定: __cdecl __fastcall与 __stdcall,三者都是调用约定(Calling convention),它决定以下内容:1)函数参数的压栈顺序,2)由调用者还是被调用者把参数 ...

  8. HttpComponents 也就是以前的httpclient项目

    HttpComponents 也就是以前的httpclient项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端/服务器编程工具包,并且它支持 HTTP 协议最新的版本和建议.不 ...

  9. Oracle基础(五):多表查询

    一.多表查询 (一)简单多表查询 1.多表查询的机制 1)SQL: SELECT * FROM emp; --14条记录 SELECT * FROM dept;--4条记录 SELECT * FROM ...

  10. 变相的取消Datagridview控件的选中状态

    思路:把每一列的文字颜色设为黑色,选中时候的背景为白色,颜色为黑色.每一列都这样设置,那么变相的达到了取消选中效果. 图: