How to display image on UIImageView using URL and NSString in ios?

后端 未结 10 2145
孤城傲影
孤城傲影 2021-01-02 16:49

I want to display image on UIImageView using URL and NSString. I am unable to show image.

My code is:

UIImageView *view_Im         


        
10条回答
  •  死守一世寂寞
    2021-01-02 17:26

    For Swift 3.0

    Synchronously:

    if let filePath = Bundle.main().pathForResource("imageName", ofType: "jpg"), image = UIImage(contentsOfFile: filePath) {
        imageView.contentMode = .scaleAspectFit
        imageView.image = image
    }
    

    Asynchronously:

    Create a method with a completion handler to get the image data from your url

    func getDataFromUrl(url:URL, completion: ((data: Data?, response: URLResponse?, error: NSError? ) -> Void)) {
        URLSession.shared().dataTask(with: url) {
            (data, response, error) in
            completion(data: data, response: response, error: error)
        }.resume()
    }
    

    Create a method to download the image (start the task)

    func downloadImage(url: URL){
        print("Download Started")
        getDataFromUrl(url: url) { (data, response, error)  in
            DispatchQueue.main.sync() { () -> Void in
                guard let data = data where error == nil else { return }
                print(response?.suggestedFilename ?? url.lastPathComponent ?? "")
                print("Download Finished")
                self.imageView.image = UIImage(data: data)
            }
        }
    }
    

    Usage:

    override func viewDidLoad() {
        super.viewDidLoad()
        print("Begin of code")
        if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
            imageView.contentMode = .scaleAspectFit
            downloadImage(url: checkedUrl)
        }
        print("End of code. The image will continue downloading in the background and it will be loaded when finished.")
    }
    

    Extension:

    extension UIImageView {
        func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
            guard let url = URL(string: link) else { return }
            contentMode = mode
            URLSession.shared().dataTask(with: url) { (data, response, error) in
                guard
                    let httpURLResponse = response as? HTTPURLResponse where httpURLResponse.statusCode == 200,
                    let mimeType = response?.mimeType where mimeType.hasPrefix("image"),
                    let data = data where error == nil,
                    let image = UIImage(data: data)
                    else { return }
                DispatchQueue.main.sync() { () -> Void in
                    self.image = image
                }
            }.resume()
        }
    }
    

    Usage:

    override func viewDidLoad() {
        super.viewDidLoad()
        print("Begin of code")
        imageView.downloadedFrom(link: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
        print("End of code. The image will continue downloading in the background and it will be loaded when finished.")
    
    }
    

提交回复
热议问题