简体   繁体   English

如何从 Firebase 远程配置中获取数组 json 的值?(Swift)

[英]How can I get array json value from Firebase remote-config ?(Swift)

I use Firebase Remote Config to compare app's version to update, but I can't get Remote Config value.我使用 Firebase Remote Config 比较要更新的应用程序版本,但无法获取 Remote Config 值。

How can I get value like array json with swift?我怎样才能得到像数组 json 和 swift 这样的值?

Here is My value这是我的价值

[
{
"version": "1.0.4",
"status": "2",
"text": "Fix Error"
}
]

And here is my code这是我的代码

Get value:获取价值:

class ConstraintValues {
static let shared = ConstraintValues()
init() {
    RemoteConfig.remoteConfig().setDefaults(["a":"b" as NSObject])
    let debugSettings = RemoteConfigSettings()
    RemoteConfig.remoteConfig().configSettings = debugSettings
}
func fetch(completetion:@escaping ( _ stringarray:String?)->()) {
    RemoteConfig.remoteConfig().fetch(withExpirationDuration: 0) { (status, error) in
        if let error = error {
            print(error)
            completetion(nil)
            return
        }
        RemoteConfig.remoteConfig().activate()
        let rc = RemoteConfig.remoteConfig().configValue(forKey: "VERSION")

        do {
            let json = try JSONSerialization.jsonObject(with: rc.dataValue, options: .allowFragments) as! [String:String]

            guard let dictionary1 = json["version"] else {return }
            guard let dictionary2 = json["text"] else {return }
            guard let dictionary3 = json["status"] else {return }
            completetion(dictionary1)
            completetion(dictionary2)
            completetion(dictionary3)
        }
        catch let error{
            print(error)
            completetion(nil)
        }

    }
}}

Check Version:检查版本:

func checkversion(controller:UIViewController){
    ConstraintValues.shared.fetch { (version) in
        let cversion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! NSString//localversion
         let url = URL(string: "https://www.google.com/")
        let appStore = version//newversion
        //Compare
        let versionCompare = cversion.compare(appStore! as String, options: .numeric)
        if versionCompare == .orderedSame {
            print("same version")
        } else if versionCompare == .orderedAscending {

            let alertc = UIAlertController(title: "UPDATE!!", message: "New Version: \(version!)", preferredStyle: .alert)
            let alertaction = UIAlertAction(title: "Update", style: .default, handler: { (ok) in
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.openURL(url!)
                }
            })
            alertc.addAction(alertaction)
            controller.present(alertc, animated: true, completion: nil)

        } else if versionCompare == .orderedDescending {

        }
    }
}

I can take "version": "1.0.4",but"text" can't get.我可以拿“version”:“1.0.4”,但是“text”拿不到。 How should I do for this method?我应该怎么做这个方法?

As you're using a JSON object, I would recommend using SwiftyJSON here.当您使用 JSON object 时,我建议在此处使用 SwiftyJSON。

install SwiftyJSON in your project在你的项目中安装SwiftyJSON

Then import SwiftyJSON at the top of your file然后在文件顶部导入SwiftyJSON

Your code should look like the following您的代码应如下所示

import Firebase
import SwiftyJSON

class MyViewController: UIViewController {
        
    var remoteConfig: RemoteConfig!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        remoteConfig = RemoteConfig.remoteConfig()
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        
        var remoteConfigDefaults = [String: NSObject]()        
        let testArr: NSArray = []
        remoteConfigDefaults["VERSION"] = testStr
        remoteConfig.setDefaults(remoteConfigDefaults)        
        
        remoteConfig.fetch() { (status, error) -> Void in
            if status == .success {
                print("Config fetched!")
                self.remoteConfig.activate() { (error) in
                    // ...
                }
            } else {
                print("Config not fetched")
                print("Error: \(error?.localizedDescription ?? "No error available.")")
            }
          
            let version = self.remoteConfig.configValue(forKey: "VERSION").jsonValue            
            let json = JSON(version)            
            print(json[0]["version"], json[0]["status"], json[0]["text"])
            
        }
    }
        
}

This solution worked for me without using SwiftyJSON该解决方案在不使用SwiftyJSON的情况下对我有用

func getSomeValue() -> SomeValue? {
    let configValue = remoteConfig?.configValue(forKey: "some_key")
    if let data = configValue?.dataValue {       
        do {
            let result = try JSONDecoder().decode(SomeValue.self, from: data)
            return result
        } catch {
            return nil
        }
    }
    return nil
}

jsonValue is now directly supported, there is no need for JSONDecoder().decode :现在直接支持 jsonValue,不需要JSONDecoder().decode

enum RemoteConfigKey: String {
        case countries_to_log
}

init() {
        remoteConfig = RemoteConfig.remoteConfig()
        let appDefaults: [String: Any?] = [
            RemoteConfigKey.countries_to_log.rawValue: ["country": ["DE"]]
        ]
        remoteConfig.setDefaults(appDefaults as? [String: NSObject])
        fetchValues()
}

var countries_to_log: [String: [String]] {
        RemoteConfig.remoteConfig().configValue(forKey: RemoteConfigKey.countries_to_log.rawValue).jsonValue as! [String : [String]]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以向 Firebase 远程配置声明一个数组吗? - Can I declare an array to Firebase Remote config? 我如何从 child 获取数组并将 firebase 保存在 swift 的结构中 - how can i get array from child and save in struct from firebase in swift Flutter - 如何将 firebase 远程配置用作 stream? - Flutter - How can I use firebase remote config as a stream? 我无法获取数组并从 Firebase 存储中放入另一个数组 swift - I can't get array and put in the another array swift from Firebase storage Firebase 远程配置:如何在 Map 中获取所有配置<string, string></string,> - Firebase Remote Config: How to get all config in Map<String, String> 如何从 Swift 和 Firebase 中的子节点获取数据数组? - How to get array of data from a child node in Swift and Firebase? 如何从 Firebase 配置中获取 measurementId? - How to get the measurementId from the Firebase config? Firebase Remote Config 随机返回错误值 - Firebase Remote Config randomly returning wrong value 如何调查 Firebase 远程配置 API 中的错误? - How to investigate errors in Firebase Remote Config API? 如何使用 firebase 数据库存储和检索数组值? - How can i stored and retrieve an array value using firebase database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM