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. python手记(41)

    python opencv图片融合 #!/usr/bin/env python #-*- coding: utf-8 -*- #code:myhaspl@qq.com import cv2 impor ...

  2. map,area标签

    map,area标签 <img src ="planets.gif" alt="Planets" usemap ="#planetmap&quo ...

  3. CentOS下安装两个或多个Tomcat7

    链接地址:http://lcbk.net/tomcat/1407.html 首先安装JDK 安装之前检查下是否已经安装了openJDK,如果已安装,建议用yum remove 卸载掉. [root@b ...

  4. 增进离岸Java开发效率的10个提示

    本文来源于我在InfoQ中文站原创的文章,原文地址是:http://www.infoq.com/cn/news/2013/12/10-tips-offshore-java-effective Cygn ...

  5. 如何用 new 来动态开辟一个二维数组

    一般的做法是: int **p = new int*[m]; //m行n列型 for (i = 0; i < m; ++i) { p[i] = new int[n]; for (j = 0; j ...

  6. iOS: 在键盘之上显示一个 View

    如 AlertView,当 show 一个 Alert 时,它会覆盖在 Keyboard 上面,不影响显示的效果.那么我们自己创建的 View 如何像 Alert 那样不被键盘盖住呢?很简单,拿到 A ...

  7. 鼠标滑轮一滚动Excel就停止工作

    鼠标滑轮一滚动Excel就停止工作 问题签名: 问题事件名称:APPCRASH 应用程序名:EXCEL.EXE 应用程序版本:15.0.4420.1017 应用程序时间戳:50673286 故障模块名 ...

  8. 从陌陌上市看BAT的移动保卫战(转)

    12 月 11 日,陌陌正式登陆纳斯达克,这件事除了证明了移动互联网“没有什么不可能之外”,对 BAT 而言,更大的意义在于需要时刻警惕还有没有其它细分领域的公司能够在自己核心业务领域溜出来. 两年前 ...

  9. 凡客副总裁被曝离职:或因IPO受阻|凡客|王春焕|离职_互联网_新浪科技_新浪网

    凡客副总裁被曝离职:或因IPO受阻|凡客|王春焕|离职_互联网_新浪科技_新浪网 凡客副总裁被曝离职:或因IPO受阻 2013年05月07日 00:56   每日经济新闻    我有话说     每经 ...

  10. 【Linux驱动器】Linux-2.6.20.4内核移植

    最近一段时间以来一直学习TQ2440内核开发板移植.嫁接驱动器. 真诚地相信这方面的知识有很大的困难,.但有一种观点认为,从看,难度越大,的提升空间的能力更大! ! 1.解压源代码 从Internet ...