Download image from url asynchronously in swift


public func imageFromServerURL(urlString: String, defaultImage : String?) {
        if let di = defaultImage {
            blogImage = UIImage(named: di)!
        }
        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                print(error ?? "error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                self.blogImage = image!
            })
        }).resume()
    }

Calling method


self.imageFromServerURL(urlString: Blog_Image.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!, defaultImage: "loading_large")