0

I have a question,and I want to show the progressView when I download the Image to my local file
I write a function to download Image, and take other question as reference.
but I don't know how to use URLSessionDownloadTak or other download progress function in my function.

This is my download function code:

func ImageFromUrl(imageView:UIImageView,url:String,chatroomId:String) {

let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(Image)/")
// create a name for your image
let fileName = url + ".jpg"
let fileURL = documentsDirectoryURL.appendingPathComponent(fileName)

let urlString = URL(string: url)

if let image = UIImage(contentsOfFile: fileURL.path)
{
    imageView.image = image
    return
}

DispatchQueue.global().async {
    let data = try? Data(contentsOf: urlString!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch

    if data != nil
    {
        if let image = UIImage(data: data!)
        {
            if !FileManager.default.fileExists(atPath: fileURL.path) {
                if let jpegData = UIImageJPEGRepresentation(image, 0.001)
                {
                    do {
                        try jpegData.write(to: fileURL, options: .atomic)
                    } catch {
                        debug(object: error)
                    }
                }
            } else {
                debug(object:"file already exists")
            }

            DispatchQueue.main.async {
                imageView.image = image//UIImage(data: data!)
            }
        }
    }
}
}
JimmyLee
  • 507
  • 2
  • 7
  • 24
  • AFAIK you have to use the following delegates: NSURLSessionDelegate and NSURLSessionDownloadDelegate You call your url with help of these: Look http://stackoverflow.com/a/38063937/4420355 it's swift 2, but the principe is the same – kuzdu May 01 '17 at 14:37

1 Answers1

1

If you want a simple solution instead of NSURLSession, I would suggest Alamofire. It has a simple method to do this kind of task.

For more information https://github.com/Alamofire/Alamofire

Alamofire.download(urlString)
    .downloadProgress { progress in
         print("Download Progress: \(progress.fractionCompleted)")
     }

     .responseData { response in
        if let data = response.result.value {
             let image = UIImage(data: data)
        }
     }
Tristan Beaton
  • 1,742
  • 2
  • 14
  • 25