Loading/Downloading image from URL on Swift

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

    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)
                            })
                        }
    

提交回复
热议问题