Kyryl Nevedrov
Kyryl Nevedrov

Reputation: 115

Swift IOS: How to download image using NSURLSession and didReciveData?

I'm a newbie in IOS development. Could you help me saying how to download image using NSURLSession and didReciveData method? I need a progress View with progress of uploading my image. I stuck after creating NSUrlSession. Please, help.

    class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {

        @IBOutlet weak var progressLabel: UILabel!
        @IBOutlet weak var imageView: UIImageView!
        @IBOutlet weak var progressView: UIProgressView!
        @IBOutlet weak var downloadButton: UIButton!

        @IBAction func downloadImage(sender: UIButton) {
            let urlString = "https://img-fotki.yandex.ru/get/6111/8955119.3/0_7e1f6_a73b98a0_orig"
            let url = NSURL(string: urlString)
           var configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
     var session: NSURLSession = NSURLSession(configuration: self.configuration)
        }

        func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
            print("didReceiveData")
        }

        func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
            print("didReceiveRes")

        }

        func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
            let alert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .Alert)
            let alertAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
            alert.addAction(alertAction)
            presentViewController(alert, animated: true, completion: nil)
        }

        func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
             print("didReceiveSendData64")
            var uploadProgress: Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
            progressView.progress = uploadProgress

        }



}

Upvotes: 2

Views: 2429

Answers (1)

Mitul Marsoniya
Mitul Marsoniya

Reputation: 5299

Help full tutorial raywenderlich : -

Monitoring Download Progress

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

// 1
if let downloadUrl = downloadTask.originalRequest?.URL?.absoluteString,
  download = activeDownloads[downloadUrl] {
  // 2
  download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
  // 3
  let totalSize = NSByteCountFormatter.stringFromByteCount(totalBytesExpectedToWrite, countStyle: NSByteCountFormatterCountStyle.Binary)
  // 4
  if let trackIndex = trackIndexForDownloadTask(downloadTask), let trackCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: trackIndex, inSection: 0)) as? TrackCell {
    dispatch_async(dispatch_get_main_queue(), {
      trackCell.progressView.progress = download.progress
      trackCell.progressLabel.text =  String(format: "%.1f%% of %@",  download.progress * 100, totalSize)
    })
}
  }
}

Upvotes: 2

Related Questions