美文网首页
Swift IOS 文件下载 进度显示

Swift IOS 文件下载 进度显示

作者: 贼噶人 | 来源:发表于2019-06-17 18:50 被阅读0次
//
//  ViewController.swift
//  Demo
//
//  Created by gang.zhou on 2018/9/22.
//  Copyright © 2018年 gang.zhou. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    private var button:UIButton? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        view.backgroundColor = UIColor.black
        button = UIButton.init(frame: CGRect.init(x: (view.frame.width * 0.1), y: (view.frame.height - 40)/2, width: (view.frame.width * 0.8), height: 40))
        button!.setTitle("This is button,click me!", for: .normal)
        button!.backgroundColor = UIColor.yellow
        button!.setTitleColor(UIColor.red, for: .normal)
        view.addSubview(button!)
        button!.addTarget(self, action:(#selector(touchDown)), for: UIControl.Event.touchDown)
        button!.addTarget(self, action:(#selector(touchUp)), for: UIControl.Event.touchUpInside)
        button!.addTarget(self, action:(#selector(touchUp)), for: UIControl.Event.touchUpOutside)
        downloadProgress = UIProgressView.init(frame: CGRect.init(x: view.frame.width * 0.1, y: 200, width: view.frame.width * 0.8, height: 20))
        view.addSubview(downloadProgress!)
    }
    
    private var downloadProgress:UIProgressView? = nil

    @objc func touchDown(){
        if let button = button {
            button.backgroundColor = UIColor.cyan
        }
        
    }
    
    @objc func touchUp(){
        if let button = button {
            button.backgroundColor = UIColor.yellow
        }
        download()
    }
    
    
    
    func download(){
        let mURLSession = URLSession.init(configuration: .default, delegate: self, delegateQueue: nil)
        mURLSession.downloadTask(with: URL.init(string: "https://vscode.cdn.azure.cn/stable/553cfb2c2205db5f15f3ee8395bbd5cf066d357d/VSCode-darwin-stable.zip")!).resume()
    }
    
}

extension ViewController:URLSessionDownloadDelegate {
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        if let downloadProgress = self.downloadProgress {
            DispatchQueue.main.async {
                downloadProgress.setProgress((Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)), animated: true)
            }
        }
    }
    
}


相关文章

网友评论

      本文标题:Swift IOS 文件下载 进度显示

      本文链接:https://www.haomeiwen.com/subject/gqmzfctx.html