我正在尝试从 url 获取图像并将其应用于按钮。出于某种原因,这起初不起作用,但随后图像在我第二次加载 View Controller 时出现。它似乎可以缓存它,然后从缓存中获取它,但不能从 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()
}
}
}
最佳答案
好的,所以我必须解决这个问题的方法是在以前的 View Controller 中加载图像,然后将其发送到 GlobalSingleton,并在加载 View 时准备好它。我不是很喜欢必须这样做,因为你不能总是这样做,它只是在我的情况下起作用。所以我希望有人能为其他人更好地回答这个问题!
关于ios - 来自网址的按钮图像未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40386633/