本篇文章記錄點擊按鈕啟動非同步傳輸下載圖片並顯示於imageView,

下載期間顯示indicator與計算下載任務完成度之百分比,

如果用網路傳輸期間有error, 請留意App Transport Security Settings是否有在info.plist設定

程式碼如下:

import UIKit

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
//        imageView.contentMode = UIViewContentMode.ScaleToFill //完全滿版(比例會失真)
//        imageView.contentMode = UIViewContentMode.ScaleAspectFit // 維持影像比例與完整圖片, 其他區域以透明顯示
        imageView.contentMode = UIViewContentMode.ScaleAspectFill //滿版與維持影像比例(部分圖像可能會被截掉)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreate  d.
    }
    
    @IBAction func buttonClicked(sender: AnyObject)
    {
        activityIndicator.startAnimating()
        
        let url = NSURL(string: "your image url")
        let sessionWithConfigure = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionWithConfigure, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        let dataTask = session.downloadTaskWithURL(url!)
        
        dataTask.resume() // 啟動task的執行
        
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
    {
        self.imageView.image = UIImage(data: NSData(contentsOfURL: location)!)
        self.activityIndicator.stopAnimating()
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64,     totalBytesExpectedToWrite: Int64)
    {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) //計算當前下載圖片之百分比
        print(NSString(format: "%.2f%%", progress*100))
    }
}
arrow
arrow
    文章標籤
    swift 非同步傳輸 indicator
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()