ios - 从 Alamofire 响应访问 JSON 值

标签 ios json swift

我正在向返回以下 JSON 的本地服务器发出请求:

{"session_key":"somecodexyz1234"}

以下代码用于尝试打印 session_key 值。但这总是被评估为nil`。

Alamofire.request(url, method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")

print("Response code: \(String(describing: response.response?.statusCode))")


if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
    print("Data: \(utf8Text)") // original server data as UTF8 string
}}

if response.data  != nil {
    let json = JSON(data: response.data!)

    // changes 
    if let arr : NSArray = json as? NSArray
    {
          let sk = arr.value(forKey: "session_key") as? String
          if sk != nil {print(sk)}
    }
}

以下是输出(print(sk) 没有执行,因为它是 nil):

Request: Optional(http://127.0.0.1:5000/code)
Response: Optional(<NSHTTPURLResponse: 0x60800023f260> { URL: http://127.0.0.1:5000/code } { status code: 200, headers {
    "Content-Length" = 40;
    "Content-Type" = "application/json";
    Date = "Sat, 23 Sep 2017 06:02:25 GMT";
    Server = "Werkzeug/0.12.2 Python/3.4.3";
} })
Response code: Optional(200)
Data: "{\"session_key\":\"somecodexyz1234\"}"

最佳答案

使用下面的代码从 json 中的 almofire 获取响应。在您的代码中,您直接检查 response.data 而不是首先检查 response.result,如下所示。

Alamofire.request(requestURL, method:.post, parameters: param as? Parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON(completionHandler: { (response) in
            switch response.result
            {
            case .success(let responseJSON):
                // If request success then you will get response in json here
                if responseJSON is String{
                    print("Reponse is string")
                }
                else if responseJSON is NSDictionary{
                    print("Reponse is Dictionary")
                }
                else if responseJSON is NSArray{
                    print("Reponse is Array")
                }
                else{
                    print("Any object")
                    return
                }
                print("Response : \((dicResponse)")

                break
            case .failure(let error):
                // If request is failure then got error here.
                break
            }
        })

关于ios - 从 Alamofire 响应访问 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46376637/

相关文章:

iphone - 如何使用 Coredata 添加和使用现有的 SQLite 数据库(x.db)?

python - 如何使用 flatten_json 递归地展平嵌套的 JSON

swift - 如何在swift中向变量添加时间函数

ios - 在 Swift 中使用 UIIamgePickerControllerDelegate 在屏幕上显示选定的图像

ios - 升级操作系统和安装 xcode 后 cocoa pod 中的 Ruby 错误

objective-c - iOS 在使用实例变量或 getter 方法时

javascript - 使用 JSON 的 AngularJs $http.post 请求

ios - 防止 Realm 写入 JSON 两次

swift - MapKit - 找到路线但未显示

iOS 应用程序文件存储。 YouTube、parse.com 还是本地?