ios - 来自网址的按钮图像未显示

标签 ios swift firebase uiimageview

我正在尝试从 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/

相关文章:

ios - 在 Swift 中运行 Firebase 数据库快速入门时遇到问题

iphone - 使用 xib 和通过代码添加的区别 - iPhone

swift - 如何声明具有类型并实现协议(protocol)的变量?

ios - Firebase 存储下载到本地文件错误

firebase - 使用 Firebase 使 URL 过期

javascript - 为什么我收到 TypeError : _this. props ."functionName"is not a function ReactJS

ios - Xcode 中的优化级别

javascript - "Preload"apple-touch-precomposed-icon 添加到主屏幕之前?

ios - 点击 didSelectRow 以转到另一个 View Controller 时崩溃

ios - 将 HKSample 与另一个 HKSample 进行比较以防止重复