How to check if json has a key without SwiftyJSON in swiftUI? - swift

I need to check a json response and find out if the response has a key.
I found other similar questions but they are working with libraries like SwiftyJSON.
I don't want to use that.
I need to know if its possible to do this without using any third party libs?
My current code is this:
let data = str.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
{
print(jsonArray)
// I NEED TO DO CHECKS HERE...
// something like this:
if (jsonArray['someKey'] = exist){
do something here
}else{
do something else
}
}
}
Is this possible at all?

Try using:
if let value = jsonArray["someKey"] {
// If key exist, this code will be executed
} else {
// If key does not exist, this code will be executed
}

Related

Issue with UserDefaults (converting data to array and back)

What I want to do:
I want to get an array from UserDefaults that I saved beforehand and append a custom object to it. Afterwards I want to encode it as a Data-type again and set this as the UserDefaults Key again.
My problem:
The encoding part is what is not working as intended for me.
It says: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x60000011a540
But I do not know how to fix this.
Below is my code for more context:
do {
let decoded = defaults.object(forKey: "ExArray") as! Data
var exo = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(decoded) as! [Exerc]
exo.append(datas[indexPath.row])
let enco = try NSKeyedArchiver.archivedData(withRootObject: exo, requiringSecureCoding: false) <- Here is the error
defaults.set(enco, forKey: "ExArray")
} catch {
print("Error encoding custom object NOSEARCHO")
}
This is how Exerc looks:
struct Exerc: Codable {
var title: String
var exID: String
}
Seems like you are not using the archiver features, so why don't you just use the codable?
do {
let key = "ExArray"
let decoded = defaults.data(forKey: key)!
var exo = try JSONDecoder().decode([Exerc].self, from: decoded)
exo.append(datas[indexPath.row])
let enco = try JSONEncoder().encode(exo)
defaults.set(enco, forKey: key)
} catch {
print("Error encoding/decoding custom object NOSEARCHO", error)
}
It just a simple refactored MVP of the original code, but you can even work a bit on this and make it human readable right in the plist file!

Remove string literals from elements inside an array

Please guys i need to parse a string to look like these in swift
"[{"question":9, "answer":25}", "question\":10, "answer":27}]"
where the index and value are dynamically gotten from a loop. I was able to get to these
["{\"question\":9, \"answer\":25}", "{\"question\":10, \"answer\":27}", "{\"question\":11, \"answer\":29}", "{\"question\":12, \"answer\":33}", "{\"question\":13, \"answer\":37}"]
so i have tried this
for i in 0..<answersForQuestionInPage.count{
let questions = answersForQuestionInPage[i] as Answer
do {
let data = try JSONEncoder().encode(questions)
// 2
let string = String(data: data, encoding: .utf8)!
answers.append(string)
print("This is the main value \(string)")
} catch{
}
}
this still gives me an array with this format
["{\"question\":9, \"answer\":25}", "{\"question\":10,
\"answer\":27}", "{\"question\":11, \"answer\":29}",
"{\"question\":12, \"answer\":33}", "{\"question\":13,
\"answer\":37}"]
with the object
"{\"question\":9, \"answer\":25}"
still wrapped in a string liteal " " what i want is for this return array to be in this format
[{"question":9, "answer":25}, {"question":10,
"answer":27}, {"question":11, "answer":29},
"{"question":12, "answer":33}, {"question":13,
"answer":37}]
I didn't understand the whole thing, but you said you need to parse the String, but I think you meant JSON. So, you can do it like this and get the values. Do let me know if it is what you needed, otherwise please add clarity in your question and I will edit and update my answer accordingly.
struct Quiz: Decodable {
let question, answer: Int
}
private func fetchQuizzes() {
//After getting the data from API, you can do this
guard let quiz = try? JSONDecoder().decode([Quiz].self,from: data) else { print("Unable to parse"); return }
print(quiz)
print(quiz.first?.answer) //First Answer
}
Just like Rob said before, you have a JSON here.
Using Robs code you decode the given JSON and create an array of Quiz objects (Robs struct).
You can now work with that array and transform it to your needs.

Multiple async request in nested for loops

I'm trying to get data from my database and after obtaining a piece of data, using that piece of data to find a new piece of data.
At the end, I can piece these together and return the derived data. I'm not sure this is the best way to approach this, but this is where im at as of now.
My problem is that each call to the database (Firebase) is async and therefore I need to somehow wait for the async to finish, before going on.
I've looked at dispatch group and heres what I have so far:
let taskGroup = DispatchGroup()
for buildingKey in building.allKeys
{
var aprt = NSDictionary()
taskGroup.enter()
// ASYNC REQUEST
getAbodesWithUID(UID: buildingKey as! String, callback: { (success, abodes) in
aprt = abodes
taskGroup.leave()
})
taskGroup.enter()
for key in aprt.allKeys
{
// ASYNC REQUEST
getTenantsWithAprt(UID: key as! String, callback: { (success, user) in
for userKey in user.allKeys
{
let dict = NSMutableDictionary()
dict.setValue(((building[buildingKey] as? NSDictionary)?["Address"] as? NSDictionary)?.allKeys[0] as? String, forKey: "Building")
dict.setValue((user[userKey] as? NSDictionary)?["Aprt"], forKey: "Number")
dict.setValue((user[userKey] as? NSDictionary)?["Name"], forKey: "Name")
dict.setValue(userKey, forKey: "UID")
dict.setValue((user[userKey] as? NSDictionary)?["PhoneNumber"], forKey: "Phone")
apartments.append(dict)
}
taskGroup.leave()
})
}
}
taskGroup.notify(queue: DispatchQueue.main, execute: {
print("DONE")
callback(true, apartments)
})
I can't seem to get it to callback properly
First, you should be iterating over aprt.allKeys inside of the callback for getAbodesWithUID, other wise, when the for loop executes aprt will be an empty dictionary.
Secondly, the taskGroup.enter() call above that for loop should be inside of the for loop, because it needs to be called once for every key. It should be placed where the // ASYNC REQUEST comment currently is.
This is precisely what "promises" are for is for. They are available in Swift via a 3rd party add-in. A popular way to do this is to push all your reads/gets into an array. Then you promise.all(yourArray) which returns the array of results/values that you then iterate over to get at each one.
From this other answer:
You can look into when which may provide what you need and is covered
here.
Use the loop to put your promises into an array and then do something
like this:
when(fulfilled: promiseArray).then { results in
// Do something
}.catch { error in
// Handle error
}

Making a variable from if statement global

While encoding JSON, I´m unwrapping stuff with an if let statement, but I'd like to make a variable globally available
do {
if
let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let jsonIsExistant = json["isExistant"]
{
// Here I would like to make jsonIsExistant globally available
}
Is this even possible? If it isn't, I could make an if statement inside of this one, but I don't think that would be clever or even possible.
delclare jsonIsExistant at the place you want it. If you are making an iOS App, than above viewDidLoad() create the variable
var jsonIsExistant: String?
then at this point use it
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let tempJsonIsExistant = json["isExistant"] {
jsonIsExistant = tempJsonIsExistant
}
}
This could be rewritten like so though
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] {
jsonIsExistant = json["isExistant"]
}
} catch {
//handle error
}
If handled the second way, then you have to check if jsonIsExistant is nil before use, or you could unwrap it immediately with a ! if you are sure it will always have a field "isExistant" every time that it succeeds at becoming json.
It doesn't make sense to expose a variable to the outside of an if let statement:
if let json = ... {
//This code will only run if json is non-nil.
//That means json is guaranteed to be non-nil here.
}
//This code will run whether or not json is nil.
//There is not a guarantee json is non-nil.
You have a few other options, depending on what you want to do:
You can put the rest of the code that needs json inside of the if. You said you didn't know if nested if statements are "clever or even possible." They're possible, and programmers use them quite often. You also could extract it into another function:
func doStuff(json: String) {
//do stuff with json
}
//...
if let json = ... {
doStuff(json: json)
}
If you know that JSON shouldn't ever be nil, you can force-unwrap it with !:
let json = ...!
You can make the variable global using a guard statement. The code inside of the guard will only run if json is nil. The body of a guard statement must exit the enclosing scope, for example by throwing an error, by returning from the function, or with a labeled break:
//throw an error
do {
guard let json = ... else {
throw SomeError
}
//do stuff with json -- it's guaranteed to be non-nil here.
}
//return from the function
guard let json = ... else {
return
}
//do stuff with json -- it's guaranteed to be non-nil here.
//labeled break
doStuff: do {
guard let json = ... else {
break doStuff
}
//do stuff with json -- it's guaranteed to be non-nil here.
}

Storing multiple values in Keychain using Locksmith

Can you store multiple key/value pairs under one forUserAccount?
try? Locksmith.saveData(["access_token" : access_token], forUserAccount: "UserData")
try? Locksmith.saveData(["email" : email!], forUserAccount: "UserData")
try? Locksmith.saveData(["markets" : market], forUserAccount: "UserData")
This code fails when looking for "email.". The only way I can do this is to create multiple forUserAccount strings: UserData, UserData1, UserData3, etc. I have tried updateData with no luck. If forUserAccount has to be unique, what is it for? It seems unnecessary if that's the case.
let userIDNumber = userID as NSNumber
let userIDString : String = userIDNumber.stringValue
let keychainData = [_keychainEmailKey: email, _keychainPasswordKey: password, _keychainUserIDKey: userIDString]
Locksmith.updateData(keychainData, forUserAccount: email)
Where _keychainEmailKey, etc are constants for keys. So forUserAccount should be unique, probably it is overriding previous values.
Just like #nyekimov's answer alludes to, a dictionary of values can be stored for an account. To clarify, here's a code snippet:
do
{
try Locksmith.saveData(["user": "notMyRealUsername", "password":"123456"], forUserAccount: "myUserAccount") //store it
let dictionary = Locksmith.loadDataForUserAccount("myUserAccount") //load it
print(dictionary) //let's see what we've got
}
catch
{
// handle errors here
}
Use try Locksmith.updateData(["user": "notMyRealUsernameEither", "password":"123456"], forUserAccount: "myUserAccount") when an account exists.