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

后端 未结 10 1950
孤城傲影
孤城傲影 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:00

    For Swift 3.0

    class ImageLoader {
    
    
    var cache = NSCache()
    
    class var sharedLoader : ImageLoader {
        struct Static {
            static let instance : ImageLoader = ImageLoader()
        }
        return Static.instance
    }
    
    func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
    
        DispatchQueue.global().async {
            let data: NSData? = self.cache.object(forKey: urlString as AnyObject) as? NSData
    
            if let goodData = data {
                let image = UIImage(data: goodData as Data)
                DispatchQueue.main.async {
                    completionHandler(image, urlString)
                }
                return
            }
    
            let url:NSURL = NSURL(string: urlString)!
            let task = URLSession.shared.dataTask(with: url as URL) {
                data, response, error in
                if (error != nil) {
                    print(error?.localizedDescription)
                    completionHandler(nil, urlString)
                    return
                }
    
                if data != nil {
                    let image = UIImage(data: data!)
                    self.cache.setObject(data as AnyObject, forKey: urlString as AnyObject)
                    DispatchQueue.main.async {
                        completionHandler(image, urlString)
                    }
                    return
                }
            }
            task.resume()
        }
    
    }
    }
    

    Usage

    ImageLoader.sharedLoader.imageForUrl(urlString: imageUrl as! String) { (image, url) in
                self.imageView.image = image
    }
    

提交回复
热议问题