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. Linux android studio :'tools.jar' seems to be not in Android Studio classpath.

    问题: 'tools.jar' seems to be not in Android Studio classpath.Please ensure JAVA_HOME points to JDK ra ...

  2. iOS/Xcode异常:reason = “The model used to open the store is incompatible with the one used to create the store”

    reason=The model used to open the store is incompatible with the one used to create the store 出现上述异常 ...

  3. POJ 1330 Nearest Common Ancestors LCA题解

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 19728   Accept ...

  4. .NET通用权限系统快速开发框架源代码

    有兴趣的朋友欢迎加群讨论:312677516 一.开发技术:B/S(.NET C# ) 1.Windows XP以上 (支援最新Win 8) 2.Microsoft Visual Studio 201 ...

  5. HDU 1862 EXCEL次序 (排序水问题)

    Problem Description Excel对能够记录一组由任意列排序指定.现在,请把你编译的代码类似特征.   Input 測试输入包括若干測试用例. 每一个測试用例的第1行包括两个整数 N ...

  6. c 求两个整数的最大公约数和最小公倍数

    //求最大公约数是用辗转相除法,最小公倍数是根据公式 m,n 的 最大公约数* m,n最小公倍数 = m*n 来计算 #include<stdio.h> //将两个整数升序排列 void ...

  7. windowsphone中获取手机位置信息

    首先在界面中加入一个textblock控件以显示信息 using System; using System.Collections.Generic; using System.IO; using Sy ...

  8. Spring通过AOP实现对Redis的缓存同步

    废话不多说 说下思路:使用aop注解,在Service实现类添加需要用到redis的方法上,当每次请求过来则对其进行拦截,如果是查询则从redis进行get key,如果是update则删除key,防 ...

  9. ZOJ 2968 Difference Game 【贪心 + 二分】

    题意: 有Ga.Gb两堆数字,初始时两堆数量相同.从一一堆中移一一个数字到另一一堆的花费定义为两堆之间数 量差的绝对值,初始时共有钱C.求移动后Ga的最小小值减Gb的最大大值可能的最大大值. 思路: ...

  10. Chapter 5.依赖倒转原则

    抽象不应该依赖谢姐,细节应该依赖于抽象:针对接口编程,不要对实现编程.例如电脑内的内存坏了不会影响到其它模块,而且什么品牌都可以插入内存插槽,而不仅限于某个品牌的内存条. A.高层模块不应该依赖底层模 ...