码迷,mamicode.com
首页 > 编程语言 > 详细

Swift - 使用NSURLSession加载数据、下载、上传文件

时间:2015-09-28 11:44:59      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:

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加载数据、下载、上传文件

标签:

原文地址:http://www.cnblogs.com/Free-Thinker/p/4843546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!