简体   繁体   中英

Getting JSON Response from API Swift

At an earlier point today, I was able to use this API and get a response in my iPhone app. The fact that I have been trying to debug this for so long is making be believe that I'm crazy! Attached is a screenshot of my console...

在此输入图像描述

Here is my code pertaining to my API call. Using Apple's URLSession and following many stack overflow questions / Tutorials I can not get this thing to work.

 let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data else {
            print("request failed \(error)")
            return
        }
        do {
            if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
                // Parse JSON
            }
        } catch let parseError {
            print("parsing error: \(parseError)")
            let responseString = String(data: data, encoding: .utf8)
            print("raw response: \(responseString)")
        }
    }
    task.resume()

Every time I get this interesting [BoringSSL] Error and the searching I've done regarding that has not produced effective in fixing whatever bug I have.

Like I said, earlier today I had this app working using the same API. I have tried the key that the website gave me and the test key they use on their site. Now that I think of it, I am going to use the exact URL from my code and the screenshot and take a screenshot from the response I get in my browser. See below:

在此输入图像描述

Received above response with the exact URL being used in my app.

tried your API in my project. It worked. You can check the difference below:

let urlTest = URL(string: "https://www.zipcodeapi.com/rest/wvyR5aWjHNUF80Z6kmr1bTuNojfzhmvtcmfBD8QNo9qbNAHy9FvBISINKF3W5i9J/multi-distance.json/99501/99501,%2085001,%2072201/km")

var request = URLRequest(url: urlTest!)

request.httpMethod = "GET"
let session = URLSession(configuration: .default)

let task : URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in

        let statusCode = (response as! HTTPURLResponse).statusCode
        if statusCode == 200{
            do {
                let json = try JSON(data:data!)
            }
            catch {
                print("Could not convert JSON data into a dictionary.")
            }
        }
    }
    task.resume()

Printing description of json: ▿ { "distances" : { "85001" : 4093.922, "72201" : 4962.6189999999997 } }

May be you have to turn off Transport Layer Security, because that worked for me.

Go to your info.plist file and add a property named App Transport Secrity Settings and set its Allow Arbitrary loads option to NO

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM