Loading/Downloading image from URL on Swift

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

提交回复
热议问题