0

Currently, I have a Struct called User, which defines the variables I want to decode from the HTTP response. Then, I have an array called users which will contain the response. As you can see, I populate users in the random8 function, but now in the random1 function I am having problems. In the random1 function, I only get 1 user instead of 8, and I am trying to take that data and replace one of the current users with that new data. I am able to do that successfully in my code (by extracting each value), but I am pretty sure I am not doing it the standard way. Please let me know if there is a better way to do this.

Keep in mind, random8 is called on viewDidLoad, and random1 occurs later on when they tap a specific button, so I am replacing the data of one specific index of users.

 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 responseObject = (try? JSONSerialization.jsonObject(with: data!)) as? [String: Any]
            print(responseObject)

            let indexFirstName = responseObject?.index(forKey: "first_name")
            let indexId = responseObject?.index(forKey: "id")
            let indexPictureURL = responseObject?.index(forKey: "picture_url")
            let indexPoints = responseObject?.index(forKey: "points")
            let indexSchool = responseObject?.index(forKey: "school")
            let indexGrade = responseObject?.index(forKey: "grade")
            let indexLastName = responseObject?.index(forKey: "last_name")

            self.users[index].last_name = responseObject![indexLastName!].value as! String
            self.users[index].first_name = responseObject![indexFirstName!].value as! String
            self.users[index].id = responseObject![indexId!].value as! Int
            self.users[index].picture_url = responseObject![indexPictureURL!].value as! String
            self.users[index].points = responseObject![indexPoints!].value as! Int
            self.users[index].school = responseObject![indexSchool!].value as! String
            self.users[index].grade = responseObject![indexGrade!].value as! Int


            DispatchQueue.main.async (
                execute: self.loadRandom8
            )

        } catch {
            print("error in getting data")
        }
    })

    task.resume()

}
4
  • Why does the implementation of getRandom1 not use JSONDecoder? Why do you create all of those indexFirstName, indexId, etc. variable and then ignore them? Commented Jul 7, 2018 at 15:50
  • I didn't know what to decode it to, since it would try decoding to an array, which doesn't work since there is only one response. Commented Jul 7, 2018 at 15:54
  • Please post your new question as a new question, not an edit to this one. Commented Jul 7, 2018 at 16:07
  • @rmaddy ok, sorry about that. I will post it separately. Commented Jul 7, 2018 at 16:07

1 Answer 1

1

Without seeing the JSON format you're getting in the random/one request it's a little hard to say, but you should be able to parse a single User instance using

let user = try JSONDecoder().decode(User.self, from: data!)

instead of resorting to JSONSerialization

and to put the data into the users array, do users[index] = user

Sign up to request clarification or add additional context in comments.

3 Comments

Now how do I get the contents of user into the specific index of users? I need the data for example to replace users[2]
users[2] = user.
I will try that, I did something similar and it didn't work, but I will try again. I will let you know in a minute if it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.