how to get double value from Firebase Remote Config in iOS? - ios

I have a default value in remote config console like the image above, I need to get that double value. in Android, I can get it like this
val remoteConfig = FirebaseRemoteConfig.getInstance()
val value = remoteConfig.getDouble("parameter_name")
but now I am confused how to get that double value for iOS, it seems there is no getDouble equivalent in swift, so what should I do ?
let remoteConfig = RemoteConfig.remoteConfig()
let value = // what should i write in here ?

You could read it as a String form the config, and then parse the String into a Double.
if let valueAsString = RemoteConfig.remoteConfig().configValue(forKey: "yourKey").stringValue {
if let valueAsDouble = Double(valueAsString) {
// you have your value as a Double now
} else {
print("Not a valid number: \(valueAsString)")
}
}
Firebase also offers "numberValue". The firebase code internally is:
[NSNumber numberWithDouble:self.stringValue.doubleValue]
This means: it returns 0 if the value cannot be converted. You have more control with the String way.

Related

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

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 ?
try this!
let numberOfDocumentsPerQuery = remoteConfig.configValue(forKey: "number_of_recommended_events_to_show_per_page").numberValue?.intValue ?? 0
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)")
}
}
Other answers didn't quite work for me. However the following did...
let numberOfDocumentsPerQuery = remoteConfig.configValue(forKey: "number_of_recommended_events_to_show_per_page").numberValue.intValue

How to force iOS Speech API to read only numbers and recognize "one" as "1"

I want to use iOS Speech API to recognize mathematical expressions. It works okay for things like two plus four times three - reads it as 2+4*3, but when I start expression with 1 it always reads it as "One". When "One" is in the middle of expression it works as expected.
I figured out that when I set SFSpeechAudioBufferRecognitionRequest property taskHint to .search when displaying live results it recognizes 1 as "1" properly at first but at the end changes it to "One"
Is there a way to configure it to recognize only numbers?
Or just force to read "One" as "1" always?
Or the only way to fix it is to format result string on my own?
I have the same problem, but looks like there is no way to configure it.
I write this extension for my code, I'm checking every segment with this.
extension String {
var numericValue: NSNumber? {
//init number formater
let numberFormater = NumberFormatter()
//check if string is numeric
numberFormater.numberStyle = .decimal
guard let number = numberFormater.number(from: self.lowercased()) else {
//check if string is spelled number
numberFormater.numberStyle = .spellOut
//change language to spanish
//numberFormater.locale = Locale(identifier: "es")
return numberFormater.number(from: self.lowercased())
}
// return converted numeric value
return number
}
}
For example
{
let numString = "1.5"
let number = numString.numericValue //1.5
// or
let numString = "Seven"
let number = numString.numericValue //7
}

Value of type 'String' has no member 'substringToIndex' not resolved

I am trying to grab currentLanguage of a device using the below function. But there has been an issue with substring and I don't seem to understand as previous answers have such simple solution of importing Foundation to the file, which didn't work for me.
class func currentLanguage() -> String
{
let str = "en-US"
if let indexOfDash = str.characters.index(of: "-")
{
let langCode = str.substringToIndex(indexOfDash)
return langCode
}
}
In addition, What can be the best approach to get current language?
You need to use
let langCode = str.substring(to: indexOfDash)
And you can get current language like that:
let pre = NSLocale.preferredLanguages[0]

Firebase uploading file getting optional string in filename

I was implementing Firebase friendly chat sample while uploading image. Getting response with optional string. what is missed?
Optional(FIRStorageMetadata 0x7fc84aced790: {
bucket = "abc.appspot.com";
contentEncoding = identity;
contentType = "image/jpeg";
downloadTokens = "abctoken";
generation = 1231231;
metageneration = 1;
name = "Optional(\"S5CKnKUykANdxSvZ3wujpMXHTvg1\")/494509700277/asset.JPG";
timeCreated = "2016-09-02T11:49:00.114Z";
updated = "2016-09-02T11:49:00.114Z";
})
My code:
let filePath = "(FIRAuth.auth()!.currentUser!.uid)/(Int(NSDate.time‌​IntervalSinceReferen‌​ceDate() * 1000))/(referenceUrl.lastPathComponent!)"
was written with optional value (?) in sample so i convert it (!)
In swift you must force unwrap value to avoid this (but make sure, it's not nil).
"\(optionalValue!)"
Or unwrap it in standard way
if let value = optionalValue {
someFIRMethod("\(value)")
}

If let condition true when value is missing in optional type, swift

I have parser in Objc, parser returns NSDictionary. I am using this parser in swift class. But when some value is missing on that dictionary, it shows nil value. e.g. ->
wirlessData = {
"anon" = {
};
"channel" = {
"text" = 1;
};
}
I am checking through
if let wepauthValue = wirlessData["wepauth"] {
if let value = wepauthValue["text"] {
print("\(value)") // nil
}
}
I don't how it satisfy the if let condition. Any one faced this types of problem can help me out.
Thanks,
vikash
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).
So, if you just want to answer the question whether the dictionary contains the key, ask:
let keyExists = dict[key] != nil
If you want the value and you know the dictionary contains the key, say:
let val = dict[key]!
But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
I have tested it and found that value is still optional.Take a look at screenshot below to understand it better.
"anon" would be an empty dictionary. An empty dictionary is not nil, it is a dictionary. Just an empty one. A JSON parser will never, ever give nil values unless you ask for a key that is not in a dictionary. For example wirlessData ["nonexistingkey"] would give you nil.
If you be more type-strong about it with the if..let's then:
if let anonValue = wirlessData["anon"] {
if let value = anonValue["text"] as? String {
// This won't execute if value isn't converted from `anonvalue["text"]` to String specifically. This includes null been a false match too
print("\(value)") // nil
}else{
print("Value did't match string at all")
}
}
or even more specifically in your case:
if let anonValue = wirlessData["anon"] {
if let value = anonValue["text"] as? Int {
// This won't execute if value isn't converted from `anonvalue["text"]` to String specifically. This includes null been a false match too
print("\(value)") // nil
}else{
print("Value did't match int at all")
}
}
The value your parser is returning not nil, its empty so you need to check on count if inner data type is dictionary or array, I have past 1 sample here
Please use below code and correct your logic accordingly to get it work properly
let wirlessData:[String:AnyObject] = [
"anon" : [],
"channel" : [
"text" : 1
]
]
if wirlessData["anon"]?.count > 0 {
if let value = wirlessData["anon"]!["text"] {
print("\(value)") // nil
}
}
Try this below code using type check operator (is) -
if wirlessData["anon"] is [String:AnyObject]
{
let anon = wirlessData["anon"]!
print(anon)
if anon["random"] is String {
let stringValue = anon["random"]!
print("\(stringValue)")
}
else if anon["random"] is Int
{
let intValue = anon["random"]!
print("\(intValue)") // nil
}
else
{
print(" may be value did't match string & Int or nil ")
}
}

Resources