Bnd10706
Bnd10706

Reputation: 2383

How to decode JSON Data in Swift

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
    }

}

Upvotes: 0

Views: 148

Answers (1)

iPriyonto
iPriyonto

Reputation: 51

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
        }
        
    }

Upvotes: 2

Related Questions