从服务器获取JSON数据

时间:2017-09-11 12:08:07

标签: ios xcode swift3

我有以下代码:

    let url:String = "https://some-service"

    var request = URLRequest(url: URL(string: url)!)

    request.httpMethod = "POST"
    let postString = ""

    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        //print("responseString = \(String(describing: responseString))")
        let dict = self.convertToDictionary(text: responseString!)

        UserDefaults.standard.set(dict, forKey: "adsDetails")
        UserDefaults.standard.synchronize()
        //self.activityIndicator.stopAnimating()
        //dump(dict)

        print("--------------------")
        dump(dict?["Birthday"]!)
        print("--------------------")

    }
    task.resume()

这是convertToDictionary函数。

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

这是结果转储

enter image description here

当我尝试提取Img的值时,我得到: 输入'任何'没有下标成员错误和构建失败

只想添加dict?[" Birthday"]只是dict的一个值。 dict还有许多其他的值,我会根据我的观点分别提取

请帮我提取Img和文本值。 那里有多组价值吗?

谢谢

1 个答案:

答案 0 :(得分:0)

尝试以下代码来提取Img和文本值:

    let responseString = String(data: data, encoding: .utf8)
    let dict = self.convertToDictionary(text: responseString!)

    if let birthday = dict?["Birthday"] as? [String: Any] {
        print(birthday["Img"])
        print(birthday["text"])
    }