Loading/Downloading image from URL on Swift

前端 未结 30 2502
感动是毒
感动是毒 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 2 with error Handle and custom request header

    Simply add extension to UIImageView:

    extension UIImageView {
        public func imageFromUrl(urlString: String) {
            if let url = NSURL(string: urlString) {
                let request = NSMutableURLRequest(URL: url)
                request.setValue("", forHTTPHeaderField: "")
                NSURLSession.sharedSession().dataTaskWithRequest(request) {
                    (data, response, error) in
                    guard let data = data where error == nil else{
                        NSLog("Image download error: \(error)")
                        return
                    }
    
                    if let httpResponse = response as? NSHTTPURLResponse{
                        if httpResponse.statusCode > 400 {
                            let errorMsg = NSString(data: data, encoding: NSUTF8StringEncoding)
                            NSLog("Image download error, statusCode: \(httpResponse.statusCode), error: \(errorMsg!)")
                            return
                        }
                    }
    
                dispatch_async(dispatch_get_main_queue(), {
                    NSLog("Image download success")
                    self.image = UIImage(data: data)
                })
                }.resume()
            }
        }
    }
    

    And then, use the new imageFromUrl(urlString: String) to download image

    Usage:

    imageView.imageFromUrl("https://i.imgur.com/ONaprQV.png")
    

提交回复
热议问题