简体   繁体   中英

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.

How can I get value like array json with 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. How should I do for this method?

As you're using a JSON object, I would recommend using SwiftyJSON here.

install SwiftyJSON in your project

Then import SwiftyJSON at the top of your file

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

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 :

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]]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM