how to get integer value from Firebase Remote Config in iOS swift?

大兔子大兔子 提交于 2020-06-17 14:11:32

问题


so I set Firebase remote config default in my iOS like this:

let remoteConfig = RemoteConfig.remoteConfig()

// set remote config default value
let defaultRemoteConfig : [String:NSObject] = [
  "number_of_recommended_events_to_show_per_page" : 15 as NSObject
]

remoteConfig.setDefaults(defaultRemoteConfig)

 // Activate and refetch remote config data. 
 // I use 'Load Value for next time' loading strategy
 remoteConfig.activate()
 remoteConfig.fetch()

and then I want to get the value from remote like this

 // get the value from remote config
let numberOfDocumentsPerQuery = remoteConfig.configValue(forKey: "number_of_recommended_events_to_show_per_page").numberValue as! Int

I need the value in Integer format, but it crash when I cast it to Int like that

here is how I set the value in the console

why is it nil ? how to fix this ?


回答1:


Make sure you've fetched in this block before getting a remote value.

func fetchCloudValues() {
  // WARNING: Don't actually do this in production!
  let fetchDuration: TimeInterval = 0

  RemoteConfig.remoteConfig().fetch(withExpirationDuration: fetchDuration) { [weak self] status, error in

    if let error = error {
      print ("Uh-oh. Got an error fetching remote values \(error)")
      return
    }

    RemoteConfig.remoteConfig().activateFetched()
    print ("Retrieved values from the cloud!")
    let numberOfEvents = RemoteConfig.remoteConfig()
                                            .configValue(forKey: "number_of_recommended_events_to_show_per_page")
                                            .intValue ?? 0
    print("Our app's number of events is \(numberOfEvents)")

  }
}



回答2:


try this!

let numberOfDocumentsPerQuery = remoteConfig.configValue(forKey: "number_of_recommended_events_to_show_per_page").numberValue?.intValue ?? 0


来源:https://stackoverflow.com/questions/60335850/how-to-get-integer-value-from-firebase-remote-config-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!