Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utilizing r.json response? #127

Open
szumlins opened this issue Jan 21, 2021 · 2 comments
Open

Utilizing r.json response? #127

szumlins opened this issue Jan 21, 2021 · 2 comments

Comments

@szumlins
Copy link

Apologies if this is a dumb question, but I am relatively new to Swift. I've implemented this in a little sandbox and can properly make a post call to my end point and get a proper response.

I'm very familiar with Python requests, so I was hoping that I would be able to address the r.json object similarly in Swift, but no matter what I do, I can't seem to figure out how to actually get key out of the r.json object. I can print it and see it is valid, but when I try to something simple (in my mind) like print(r.json["my_key"]) I can't.

This is probably more of a lack of understanding of the object type that r.json returns in swift and how to get info out of it, but I figured I'd ask because I love the idea of just using my familiarity with Python requests to start my voyage into Swift programming.

@aldo-o
Copy link

aldo-o commented Jun 11, 2021

I believe you have to cast it first.

let result = r.json! as! [String: String]

print(result["my_key"])

I am new as well, so I'm not sure if there is a better approach, but Python and Swift are very different languages. Python is interpreted language and Swift is a compiled language. So you have to cast it first.
If you want my suggestion, do not use this kind of approach in Swift unless it's only for debug purposes. Create a Model class first, after getting the response, add the response to the Model class that you created.

This is an example when using Reddit api to login:

LoginModel.swift

struct LoginModel: Decodable {
    let access_token: String
    let expires_in: Int
    let scope: String
    let token_type: String
}

And after getting the response from Just you just have to write this code:

if r.ok {
    let resp = try? JSONDecoder().decode(LoginModel.self, from: r.content!)
}

Then you can get the values:

print(resp.access_token)

@szumlins
Copy link
Author

Thank you for this! I'll give it a try.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants