NSURLSession的使用

//
//  ViewController.swift
//  session使用
//
//  Created by zhang on 16/2/28.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,NSURLSessionDownloadDelegate {

    @IBOutlet weak var progress: UIProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.downloadA()
    }
    // oc的代理是强引用,swift的不是
    lazy var session:NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
    // 存放task
    var task:NSURLSessionDownloadTask?
    // 存放断点续传的数据
    var resumeData:NSData?
    // 可以显示下载进度,暂停继续的下载
    @IBAction func start(button:UIButton)
    {
        // 初始化task
        self.task = session.downloadTaskWithURL(NSURL(string: "http://localhost/1.mp4")!)
        // 初始化data
        self.resumeData = nil
        // 开始
        self.task?.resume()
    }
    // 停
    @IBAction func stop(button:UIButton)
    {
        // 停止
        self.task?.cancelByProducingResumeData({ (data:NSData?) -> Void in
            // 记录当前data
            self.resumeData = data
            // 置空task
            self.task = nil
        })
        print(self.task)
    }
    // 继续
    @IBAction func resume(button:UIButton)
    {
        if self.resumeData != nil
        {
            // 根据上次暂停时的data初始化task
            self.task = session.downloadTaskWithResumeData(self.resumeData!)
            // 初始化data
            self.resumeData = nil
            // 继续
            self.task?.resume()
        }
        else
        {
            print("没有暂停过的任务或者有任务正在运行")
        }

    }
    // 下载完成时执行
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        print("下载完成了")
    }
    // 下载进度发生变化时执行
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
            self.progress.progress = Float(Float64(totalBytesWritten) / Float64(totalBytesExpectedToWrite))
        }
    }
    // 下载和解压zip,需要用到第三方的库
    func downloadA()
    {
        let downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(NSURL(string: "http://localhost/zip.zip")!) { (url:NSURL?, response:NSURLResponse?, error:NSError?) -> Void in
            SSZipArchive.unzipFileAtPath(url?.path, toDestination: "/Users/zhang/Desktop/path/")
        }
        downloadTask.resume()
    }
    // 发送请求
    func request()
    {
        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithURL(NSURL(string: "http://localhost/demo.json")!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

            print(try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments))
        }
        dataTask.resume()
    }
}

标签: swift, 网络

添加新评论