【问题标题】:Button image from url not showing up来自 url 的按钮图像未显示
【发布时间】: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


    【解决方案1】:

    好的,所以我必须解决这个问题的方法是将图像加载到以前的视图控制器中,然后将其发送到 GlobalSingleton,并在加载视图时准备好它。我不是真的喜欢这样做,因为你不能总是这样做,它只是在我的情况下工作。所以我希望有人可以为其他人更好地回答这个问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2021-10-14
      • 2018-08-27
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多