Farlanki.

NSURLSession

字数统计: 198阅读时长: 1 min
2014/12/17 Share
1
2
3
4
5
6
7
8
9
10
11
12
var getImageTask:NSURLSessionDownloadTask =
self.session!.downloadTaskWithURL(NSURL(string:imageUrlBasic), completionHandler: { (url:NSURL!, response:NSURLResponse!, error:NSError!) -> Void in
// handle dwnloaded data
var data = NSData(contentsOfURL:url!)
var downloadedImage:UIImage = UIImage(data:data)
dispatch_async(dispatch_get_main_queue()){
// do stuff with image
self.myImageView.image = downloadedImage
println("downloadtask with closure")
self.myLabel.text = "downloadtask with closure"
}
})

创建一个图片下载任务,NSURL是下载任务网址,completionHandler指定任务完成后的回调代码块,responce是一个闭包,任务完成后在主线程更新imageview

过程:
Image

在 downloadtask 中

  • download task convenience methods. When a download successfully
  • completes, the NSURL will point to a file that must be read or
  • copied during the invocation of the completion routine. The file
  • will be removed automatically.
    下载任务完成后,调用协议的
1
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){}

方法

dataTaskWithRequest过程:

1.创建一个NSMutableURLRequest类

2.用NSMutableURLRequest作为参数创建一个任务,类为dataTaskWithURL

参考

CATALOG