NSURLSession加载数据 下载上传

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()
               }
        
             }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值