Downloading and parsing json in swift

前端 未结 9 1206
独厮守ぢ
独厮守ぢ 2020-12-02 05:37

I\'m trying to get the JSON from a website and parse it before putting it inside of an iOS view.

Here\'s my code;

func startConnection(){
        le         


        
9条回答
  •  情歌与酒
    2020-12-02 06:14

    The answer of @david72 worked perfectly for me. So here's the same in Swift 3 and URLSession for your convenience. Also with some added error printing for easier debugging.

    func getHttpData(urlAddress : String)
    {
        // Asynchronous Http call to your api url, using NSURLSession:
        guard let url = URL(string: urlAddress) else
        {
            print("Url conversion issue.")
            return
        }
        URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
            // Check if data was received successfully
            if error == nil && data != nil {
                do {
                    // Convert NSData to Dictionary where keys are of type String, and values are of any type
                    let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                    print(json)
                    // Access specific key with value of type String
                    // let str = json["key"] as! String
                } catch {
                    print(error)
                    // Something went wrong
                }
            }
            else if error != nil
            {
                print(error)
            }
        }).resume()
    }
    

提交回复
热议问题