0

So I am having a hard time understanding how swift handles API data.

My app calls for a Bearer token, and the API returns a Token and Expires , i need to extract the token so i can make another API call later.

i can see in the print statement the token and expires data, but how do i extract just the token out.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

class MyRequestController {
    func getToken() {
    
        let semaphore = DispatchSemaphore (value: 0)

        var request = URLRequest(url: URL(string: "URL")!,timeoutInterval: Double.infinity)
        request.addValue("Basic userinfo", forHTTPHeaderField: "Authorization")
        request.addValue("AWSALB=efzS5NSzJXZ4OpGhrFJLjdemrPBlAW5H36T6T5AVneKb+5F9PGVi1VMmBpGe8SKom145AhE2MM6vZAvLGFVQezt2qG6hC8a12mshJewTwJYJFq9YCDfkK49kRhdE; AWSALBCORS=efzS5NSzJXZ4OpGhrFJLjdemrPBlAW5H36T6T5AVneKb+5F9PGVi1VMmBpGe8SKom145AhE2MM6vZAvLGFVQezt2qG6hC8a12mshJewTwJYJFq9YCDfkK49kRhdE", forHTTPHeaderField: "Cookie")

        request.httpMethod = "POST"

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
          guard let data = data else {
            print(String(describing: error))
            semaphore.signal()
            return
          }
            print(String(data: data, encoding: .utf8)!)
          semaphore.signal()
        }

        task.resume()
        semaphore.wait()
    }
    
    struct TokenInfo: Decodable {
        let token: String
    }

}
1
  • Research Codable with JSONDecoder or use JSONSerialization Commented Apr 15, 2022 at 19:18

1 Answer 1

2

I am assuming the TokenInfo is your desired output from this method. You are on the right track. The next step is to convert the data into TokenInfo model using JSONDecoder.

    import Foundation
    #if canImport(FoundationNetworking)
    import FoundationNetworking
    #endif
    
    class MyRequestController {
        func getToken() {
            
            let semaphore = DispatchSemaphore (value: 0)
            
            var request = URLRequest(url: URL(string: "URL")!,timeoutInterval: Double.infinity)
            request.addValue("Basic userinfo", forHTTPHeaderField: "Authorization")
            request.addValue("AWSALB=efzS5NSzJXZ4OpGhrFJLjdemrPBlAW5H36T6T5AVneKb+5F9PGVi1VMmBpGe8SKom145AhE2MM6vZAvLGFVQezt2qG6hC8a12mshJewTwJYJFq9YCDfkK49kRhdE; AWSALBCORS=efzS5NSzJXZ4OpGhrFJLjdemrPBlAW5H36T6T5AVneKb+5F9PGVi1VMmBpGe8SKom145AhE2MM6vZAvLGFVQezt2qG6hC8a12mshJewTwJYJFq9YCDfkK49kRhdE", forHTTPHeaderField: "Cookie")
            
            request.httpMethod = "POST"
            
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data else {
                    print(String(describing: error))
                    semaphore.signal()
                    return
                }
                do {
                    let tokenData = try JSONDecoded().decode(TokenInfo.self, from: data)
                    // Do something with tokenData
                    // Print(tokenData.token)
                } catch {
                    // Handle error
                }
                semaphore.signal()
            }
            
            task.resume()
            semaphore.wait()
        }
        
        struct TokenInfo: Decodable {
            let token: String
        }
        
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I was close, but quick question, when i do this. Data().token = jsonData.token the value is not stored. am i missing something with this?I have a data model Data() where I am storing my API data, and i want to store the token there for sure later in the applciation.
If you want to store the token for later use for different endpoints you will have to store it. There are several ways to do it. You can store it using UserDefaults with a couple of lines of codes although it is not recommended at all. For sensitive information like auth token should be stored in Keychain.

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.