Loading/Downloading image from URL on Swift

前端 未结 30 2564
感动是毒
感动是毒 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:08

    swift 5

    extension UIImageView {
        func load(url: URL) {
            DispatchQueue.global().async { [weak self] in
                if let data = try? Data(contentsOf: url) {
                    if let image = UIImage(data: data) {
                        DispatchQueue.main.async {
                            self?.image = image
                        }
                    }
                }
            }
        }
    }
    

    for using

    override func awakeFromNib() {
        super.awakeFromNib()
        imgView.load(url: "<imageURLHere>")
    }
    
    0 讨论(0)
  • 2020-11-21 06:08

    Image loading from server :-

    func downloadImage(from url: URL , success:@escaping((_ image:UIImage)->()),failure:@escaping ((_ msg:String)->())){
        print("Download Started")
        getData(from: url) { data, response, error in
            guard let data = data, error == nil else {
                failure("Image cant download from G+ or fb server")
                return
            }
    
            print(response?.suggestedFilename ?? url.lastPathComponent)
            print("Download Finished")
            DispatchQueue.main.async() {
                 if let _img = UIImage(data: data){
                      success(_img)
                }
            }
        }
    }
    func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
        URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
    }
    

    Usage :-

      if let url = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
                            self.downloadImage(from:url , success: { (image) in
                                print(image)
    
                            }, failure: { (failureReason) in
                                print(failureReason)
                            })
                        }
    
    0 讨论(0)
  • 2020-11-21 06:11

    Swift 4

    This method will download an image from a website asynchronously and cache it:

        func getImageFromWeb(_ urlString: String, closure: @escaping (UIImage?) -> ()) {
            guard let url = URL(string: urlString) else {
    return closure(nil)
            }
            let task = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
                guard error == nil else {
                    print("error: \(String(describing: error))")
                    return closure(nil)
                }
                guard response != nil else {
                    print("no response")
                    return closure(nil)
                }
                guard data != nil else {
                    print("no data")
                    return closure(nil)
                }
                DispatchQueue.main.async {
                    closure(UIImage(data: data!))
                }
            }; task.resume()
        }
    

    In use:

        getImageFromWeb("http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") { (image) in
            if let image = image {
                let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
                imageView.image = image
                self.view.addSubview(imageView)
            } // if you use an Else statement, it will be in background
        }
    
    0 讨论(0)
  • 2020-11-21 06:12

    Xcode 8Swift 3

    Leo Dabus's answer is awesome! I just wanted to provide an all-in-one function solution:

    let url = URL(string: 
        "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
    
    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
        guard let data = data, error == nil else { return }
    
        DispatchQueue.main.async() {    // execute on main thread
            self.imageView.image = UIImage(data: data)
        }
    }
    
    task.resume()
    
    0 讨论(0)
  • 2020-11-21 06:13

    You can use pod SDWebImage to achieve the same. Its easy to use. Yo can get documentaion here SDWebImage

    Here is the sample code

    self.yourImage.sd_setImage(with: NSURL(string: StrUrl as String ) as URL!, placeholderImage: placeholderImage, options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
                    if( error != nil)
                    {
                        print("Error while displaying image" , (error?.localizedDescription)! as String)
                    }
                })
    
    0 讨论(0)
  • 2020-11-21 06:14
    class func downloadImageFromUrl(with urlStr: String, andCompletionHandler:@escaping (_ result:Bool) -> Void) {
            guard let url = URL(string: urlStr) else {
                andCompletionHandler(false)
                return
            }
            DispatchQueue.global(qos: .background).async {
                URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
                    if error == nil {
                        let httpURLResponse = response as? HTTPURLResponse
                        Utils.print( "status code ID : \(String(describing: httpURLResponse?.statusCode))")
                        if httpURLResponse?.statusCode == 200 {
                            if let data = data {
                                if let image = UIImage(data: data) {
                                    ImageCaching.sharedInterface().setImage(image, withID: url.absoluteString as NSString)
                                    DispatchQueue.main.async {
                                        andCompletionHandler(true)
                                    }
                                }else {
                                    andCompletionHandler(false)
                                }
                            }else {
                                andCompletionHandler(false)
                            }
                        }else {
                            andCompletionHandler(false)
                        }
                    }else {
                        andCompletionHandler(false)
                    }
                }).resume()
            }
        }
    

    I have created a simple class function in my Utils.swift class for calling that method you can simply accesss by classname.methodname and your images are saved in NSCache using ImageCaching.swift class

    Utils.downloadImageFromUrl(with: URL, andCompletionHandler: { (isDownloaded) in
                                if isDownloaded {
                                    if  let image = ImageCaching.sharedInterface().getImage(URL as NSString) {
                                        self.btnTeam.setBackgroundImage(image, for: .normal)
                                    }
                                }else {
                                    DispatchQueue.main.async {
                                        self.btnTeam.setBackgroundImage(#imageLiteral(resourceName: "com"), for: .normal)
                                    }
                                }
                            })
    

    Happy Codding. Cheers:)

    0 讨论(0)
提交回复
热议问题