如何在Swift中存储JSON post响应的一个特定元素

时间:2018-01-24 18:08:14

标签: swift http networking

我有一个快速程序,可以为rails应用程序创建一个成功的JSON帖子。这是回复:

Optional(<NSHTTPURLResponse: 0x604000226280> { URL: http://groupsyncenv.rtimfc7m2.eu-west-1.elasticbeanstalk.com/login_post } { Status Code: 200, Headers {
"Cache-Control" =     (
    "max-age=0, private, must-revalidate"
);
Connection =     (
    close
);
"Content-Length" =     (
    618
);
"Content-Type" =     (
    "application/json; charset=utf-8"
);
Date =     (
    "Wed, 24 Jan 2018 17:57:52 GMT"
);
Etag =     (
    "W/\"c34b1ba0f3cfbd53ef65a30eddd47c50\""
);
Server =     (
    "nginx/1.12.1"
);
Via =     (
    "1.1 m00180A4E4E3C (squid/3.5.23)"
);
"X-Cache" =     (
    "MISS from m00180A4E4E3C"
);
"X-Cache-Lookup" =     (
    "MISS from m00180A4E4E3C:3128"
);
"X-Content-Type-Options" =     (
    nosniff
);
"X-Frame-Options" =     (
    SAMEORIGIN
);
"X-Request-Id" =     (
    "9bf3c1fa-e362-4d59-8396-8540981f1d36"
);
"X-Runtime" =     (
    "0.092878"
);
"X-XSS-Protection" =     (
    "1; mode=block"
);

我需要的所有代码都是与响应相关联的数字&#34; X-Request-Id&#34;但我不知道怎么做。我的快速计划如下:

func loginPost(){

    let headers = [
        "Content-Type": "application/json",
        "Cache-Control": "no-cache",
        "Postman-Token": "b5468cec-292a-6c60-d195-6e270909e54b"
    ]
    let parameters = [
        "email": "sample@email.com",
        "password": "password123"
        ] as [String : Any]

    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
    guard let data = postData else {
        return
    }

    let request = NSMutableURLRequest(url: NSURL(string: "http://groupsyncenv.rtimfc7um2.eu-west-1.elasticbeanstalk.com/login_post")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as? Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse)
        }
    })

    dataTask.resume()

}

正如您所看到的,我只是打印Http响应,我知道这是错误的,但我无法弄清楚如何在这里访问单个元素。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以通过调用URLResponse HTTPURLResponseresponse.allHeaderFields对象转换为Dictionary来简单地访问HTTP标头,这样您就可以使用订阅来获取与特定键对应的值。

一些通用建议:除非您有充分的理由这样做,否则不要使用旧的Foundation数据类型。使用他们的原生Swift替代品。在创建它们之后立即将Foundation对象转换为其Swift替代品时尤其如此,因为Swift API需要Swift类型,例如URLRequest而不是NSMutableURLRequest和{{1而不是URL

NSURL