Search code examples
iosswiftswift4nsjsonserialization

convert JSONresponse to NSDATA or NSDICTIONARY in swift4


I get a response from a public test api in swift as a JSONarray:

func getFlightData(airportCode: String, minutesBehind: String, minutesAhead:String){
    let securityToken: String = "Basic YWFnZTQxNDAxMjgwODYyNDk3NWFiYWNhZjlhNjZjMDRlMWY6ODYyYTk0NTFhYjliNGY1M2EwZWJiOWI2ZWQ1ZjYwOGM="
    var headers: HTTPHeaders = [:]
    headers["Authorization"] = securityToken
    let parameters: Parameters = ["city": airportCode, "minutesBehind" : minutesBehind, "miutesAhead" :minutesAhead]
            Alamofire.request("https://api.qa.alaskaair.com/1/airports/"+airportCode+"/flights/flightInfo", parameters: parameters, headers: headers).responseJSON { (response) in
        print(response)

    }

I have used almofire in swift4 to achieve this operation.

Should I convert this JSONArray to NSData or NSDictionary? and How? Do I have to use JSONSerealization?


Solution

  • You are already using Alamofire as your network requester, So it is not necessary to convert the response object to JSON object or Data object. The library itself will provide to parsed JSON object. So check the below sample code to check the JSON object.

        let urlString = "https://......"
        let securityToken: String = "Basic YWFnZTQxNDAxMjgwODYyNDk3NWFiYWNhZjlhNjZjMDRlMWY6ODYyYTk0NTFhYjliNGY1M2EwZWJiOWI2ZWQ1ZjYwOGM="
        var headers: HTTPHeaders = [:]
        headers["Authorization"] = securityToken
        let parameters: Parameters = ["city": 100, "minutesBehind" : 60, "miutesAhead" :0]
        Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
            if let jsonObject = response.result.value{
                print("response.result.value \(String(describing: jsonObject))")
            }
    
            if let jsonObject = response.value{
                print("response.value \(String(describing: jsonObject))")
            }
        }