NSURLSession类支持三种类型的任务 :加载数据 下载和上传 为data task download task 和 upload task session task是整个NSURLSeesion架构的核心
//加载数据 func sessionLoadData() { //创建NSURL对象 var url = NSURL(string: "http://m.weather.com.cn/data/101010100/html") //创建请求的对象 var request = NSURLRequest(URL: url!) let session = NSURLSession.sharedSession() var dataTask = session.dataTaskWithRequest(request, completionHandler: { (data:NSData?, resp:NSURLResponse?, error:NSError?) -> Void in //返回错误的情况 if error != nil { print(error?.code) print(error?.description) }else { var jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding) print(jsonString) } })as NSURLSessionTask //使用resume方法启动任务 dataTask.resume() }
//加载数据 func sessionSimpleDownLoad() { //创建NSURL对象 var url = NSURL(string: "http://m.weather.com.cn/data/101010100/html") //创建请求的对象 var request = NSURLRequest(URL: url!) let session = NSURLSession.sharedSession() var dataDownLoadTask = session.downloadTaskWithRequest(request) { (var location:NSURL?, resp:NSURLResponse?, error:NSError?) -> Void in //输出下载文件原来的存放目录 print("location:\(location)") //location的位置转化 var locationPath = location?.path //拷贝到自己的目录中 let document = NSHomeDirectory() + "/Documents/1.jpg" //创建文件的管理器 do { self.fileManger = try NSFileManager.defaultManager() } catch{ print("创建文件管理器失误") } do { try self.fileManger.moveItemAtPath(locationPath!, toPath: document) } catch{ print("转化路径失败") } } //输出文件路径 print("location \(document)") //使用resume方法启动任务 dataDownLoadTask.resume() }
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { //下载结束的时候 print("下载结束") } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { //获取进度 var written = (CGFloat)(bytesWritten) var total = (CGFloat)(totalBytesExpectedToWrite) //目前的进度 现在的除以总共的 var pro = written / total print("下载进度\(pro)") } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { //下载偏移 主要用于暂停续传 print("下载偏移") }
func sessionUpload() { //创建NSURL对象 var url = NSURL(string: "http://m.weather.com.cn/data/101010100/html") //创建请求的对象 var request = NSURLRequest(URL: url!) let session = NSURLSession.sharedSession() //上传的数据流 var document = NSHomeDirectory() + "/Documents/1.jpg" var imageData = NSData(contentsOfFile: document) //上传的任务 var uploadTask = session.uploadTaskWithRequest(request, fromData: imageData) { (data:NSData?, resp:NSURLResponse?, error:NSError?) -> Void in //上传完毕之后判断 print("上传完毕") } //执行任务 uploadTask.resume() } }