NSURLSession 下载文件 --Swift

var session:NSURLSession?
var Downloadtask:NSURLSessionDownloadTask?

let url = NSURL(string: "http://yinyueshiting.baidu.com/data2/music/134378339/13611644158400128.mp3?xcode=6f254cc3b54ee63ce4d6351b3c1b445d")

let config = NSURLSessionConfiguration.defaultSessionConfiguration()

session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

Downloadtask = session?.downloadTaskWithURL(url!)

Downloadtask?.resume()

/**
     下载成功的回调 NSURLSessionDownloadDelegate
*/
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
        waveProgressView.percent = 1
        waveProgressView.startWave()
        var fileString = NSHomeDirectory() as NSString
        fileString = fileString.stringByAppendingPathComponent("/Documents/")
        let fileName = "/icon.zip"
        let manager = NSFileManager.defaultManager()
        let url = NSURL(fileURLWithPath: "\(fileString)\(fileName)")
        do{
            //删除原来的
          try?  manager.removeItemAtURL(url)
          try?  manager.removeItemAtURL(NSURL(fileURLWithPath: G_DOCUMENTS_PIC))
            //从tmp路径移动到Documents
          try?  manager.moveItemAtURL(location, toURL: url)

        }catch{

        }
        //在Documents解压缩
        SSZipArchive.unzipFileAtPath("\(fileString)\(fileName)", toDestination: G_DOCUMENTS)
        showLabel.text = "正在处理资源文件"
        self.delay(2.5) { [weak self]() -> () in
            self!.loginInfo()
        }

    }

/**
     下载时候的回调
     */
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
//        if(canChange){
            progress = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite)
            let progressStr = Double(progress * 100).analyzingString(".2f")
            showLabel.text = "正在努力加载\(progressStr)%"
//        }
    }

如有看不懂请参照:http://blog.csdn.net/xn4545945/article/details/37919697

http://www.cocoachina.com/ios/20160601/16544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值