Reputation: 524
I am trying to get an image from a url and apply it to a button. For some reason this doesn't work at first but then the image shows up the 2nd time I load the view controller. It seems like it can cache it, then later get it from cache, but can't show it from url, only from cache, it would appear. This is the code, I am getting the image from Firebase.
DataService.ds.REF_USERS.child(self.loggedInUserId!).observeEventType(.Value, withBlock: { userDictionary in
let userDict = userDictionary.value as! NSDictionary
let profileThumbUrl = userDict.objectForKey("profileThumbUrl") as! String
self.button.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
let profileThumbImage = UIImageView()
if profileThumbUrl != "" {
profileThumbImage.loadImageUsingCacheWithUrlString(profileThumbUrl)
self.button.setImage(profileThumbImage.image, forState: .Normal)
} else {
self.button.setImage(UIImage(named: "defaultUserSmall"), forState: .Normal)
}
})
The function that I use to get the image from url and cache it, or load from cache is as follows. I use it other places in the app and it works fine, but when I try to use it on this button it seems to not show it loaded from url, but it caches it and will show it from cache:
var imageCache = NSMutableDictionary()
extension UIImageView {
func loadImageUsingCacheWithUrlString(urlString: String) {
self.image = nil
if let img = imageCache.valueForKey(urlString) as? UIImage{
self.image = img
}
else{
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
if(error == nil){
if let img = UIImage(data: data!) {
imageCache.setValue(img, forKey: urlString) // Image saved for cache
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = img
})
}
}
})
task.resume()
}
}
}
Upvotes: 1
Views: 98
Reputation: 524
Ok so the way I had to solve this was to load the image in a previous view controller, then send it to a GlobalSingleton, and have it ready when the view loaded. I'm not real fond of having to do this because you can't always do this, it just worked in my case. So I hope someone has a better answer to this question for other people!
Upvotes: 1