How to use a Data from JSON response into a variable in Swift

Viewed 120

I'm trying to use an object (web href - from response) from the JSON Response, that I later want to convert into a variable. But at the moment I'm only able to get the entire JSON response.

What I need is just one URL out of it.

My Code

import UIKit

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

var semaphore = DispatchSemaphore (value: 0)

let parameters = "{\n    \"customerInternalReference\":\"William's Swift Bootcamp\",\n    \"workflowDefinition\":{\n        \"key\": 10015\n    },\n    \"userReference\": \"Lets get swifty\",\n    \"tokenLifetime\": \"100m\"\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "https://urlhere.com")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Basic masked for security", forHTTPHeaderField: "Authorization")

request.httpMethod = "POST"
request.httpBody = postData

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 response = try JSONSerialization.jsonObject(with: data)
              
              print(response)
    }
    
    catch{
        print(error)
}
    
  semaphore.signal()
}


task.resume()
semaphore.wait()

My Response (Displayed in Debug Area)

{
    account =     {
        id = "accountidcomeshere";
    };
    sdk =     {
        token = "tokkencomeshere";
    };
    timestamp = "2022-09-13T21:35:07.347Z";
    web =     {
        href = "https:urlcomeshere.com/needThis/";
    };
    
}
1 Answers

try something like this approach to get to the href element of the response:

let response = try JSONSerialization.jsonObject(with: data) as! [String : Any]
print("\n-----> response: \(response)")

if let web = (response["web"] as? [String : String]),
   let href = web["href"] {
    print("\n--> href: \(href)") // --> href: https:urlcomeshere.com/needThis/
}

Note, using DispatchSemaphore seems to be from the dark ages, there are more modern ways to achieve an API call.

Related