Here, I am getting a random user and replacing a user in the users array. However, I want to check to see if that user i just got from the random1 is already in the users. I would like to check by their id. I know it has to be an if statement, but I don't know how to actually check if it is contained in users. Also, in the body of the if statement, I will have to do recursion. If I call itself again, can I just pass getRandom1(index:index), or will it not remember anymore what index was when I originally called it?
struct User: Decodable {
var id: Int
var first_name: String
var last_name: String
var picture_url: String
var points: Int
var school: String
var grade: Int
}
var users = [User]()
func getRandom8() {
let url = URL(string: "https://somewebsite.com/users/random/eight")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
let preferences = UserDefaults.standard
request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
do {
self.users = try JSONDecoder().decode([User].self, from: data!)
DispatchQueue.main.async (
execute: self.loadRandom8
)
} catch {
print("error in getting data")
}
})
task.resume()
}
func getRandom1(index:Int) {
let url = URL(string: "https://somewebsite.com/users/random/one")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
let preferences = UserDefaults.standard
request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
//write a statement that says if that user is already there, do the call again
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
do {
let user = try JSONDecoder().decode(User.self, from: data!)
self.users[index] = user
//if statement should go here
DispatchQueue.main.async (
execute: self.loadRandom8
)
} catch {
print("error in getting data")
}
})
task.resume()
}
Aucun commentaire:
Enregistrer un commentaire