Loading/Downloading image from URL on Swift

前端 未结 30 2513
感动是毒
感动是毒 2020-11-21 05:39

I\'d like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I\'ve a compilation error:

30条回答
  •  情深已故
    2020-11-21 06:04

    swift 3 with error handling

    let url = URL(string: arr[indexPath.row] as! String)
    if url != nil {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
            DispatchQueue.main.async {
                if data != nil {
                    cell.imgView.image = UIImage(data:data!)
                }else{
                    cell.imgView.image = UIImage(named: "default.png")
                }
            }
        }
    }
    

    With Extension

    extension UIImageView {
    
        func setCustomImage(_ imgURLString: String?) {
            guard let imageURLString = imgURLString else {
                self.image = UIImage(named: "default.png")
                return
            }
            DispatchQueue.global().async { [weak self] in
                let data = try? Data(contentsOf: URL(string: imageURLString)!)
                DispatchQueue.main.async {
                    self?.image = data != nil ? UIImage(data: data!) : UIImage(named: "default.png")
                }
            }
        }
    }
    

    Extension Usage

    myImageView. setCustomImage("url")
    

    With Cache support

    let imageCache = NSCache()
    
    extension UIImageView {
    
        func loadImageUsingCacheWithURLString(_ URLString: String, placeHolder: UIImage?) {
    
            self.image = nil
            if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
                self.image = cachedImage
                return
            }
    
            if let url = URL(string: URLString) {
                URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
    
                    //print("RESPONSE FROM API: \(response)")
                    if error != nil {
                        print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
                        DispatchQueue.main.async { [weak self] in
                            self?.image = placeHolder
                        }
                        return
                    }
                    DispatchQueue.main.async { [weak self] in
                        if let data = data {
                            if let downloadedImage = UIImage(data: data) {
                                imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
                                self?.image = downloadedImage
                            }
                        }
                    }
                }).resume()
            }
        }
    }
    

提交回复
热议问题