【发布时间】:2016-11-02 17:55:12
【问题描述】:
我正在尝试从 url 获取图像并将其应用于按钮。出于某种原因,这起初不起作用,但随后图像在我第二次加载视图控制器时出现。似乎它可以缓存它,然后从缓存中获取它,但无法从 url 显示它,只能从缓存中显示它。这是代码,我从 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)
}
})
我用来从 url 获取图像并缓存它,或者从缓存加载的函数如下。我在应用程序的其他地方使用它,它工作正常,但是当我尝试在这个按钮上使用它时,它似乎没有显示它是从 url 加载的,但它会缓存它并从缓存中显示它:
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()
}
}
}
【问题讨论】:
标签: ios swift firebase uiimageview