简体   繁体   English

如何在Swift中查看来自HTTP GET请求的服务器响应?

[英]How can I see the server response from an HTTP GET request in Swift?

I'm using a RESTless API to make database queries to check for things like unique usernames and emails. 我正在使用RESTless API进行数据库查询,以检查诸如唯一的用户名和电子邮件之类的内容。 However I'm not sure how to get the server code from the response compared to getting the return dictionary. 但是,我不确定与从返回字典相比,如何从响应中获取服务器代码。 For some searches if there's no result found it returns 404 and a non empty dictionary. 对于某些搜索,如果没有找到结果,则返回404和非空字典。 So I can't simply check if the return dict is empty. 所以我不能简单地检查return dict是否为空。

do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
    }
    catch {
        print("failure")
    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTaskWithRequest(request) {
        data, response, error in

        // Check for error
        if error != nil
        {
            print("error=\(error)")
            return
        }

        // Print out response string
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")


        // Convert server json response to NSDictionary
        do {
            if let convertedJsonIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                // Print out dictionary
                print(convertedJsonIntoDict)
                convertedDict = convertedJsonIntoDict
            }
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }

    }

    task.resume()

    return convertedDict ?? nil

There is data about the response in the response object passed in to the completion handler. 传递给完成处理程序的response对象中包含有关响应的数据。 For HTTP/HTTPS requests it's an NSHTTPURLResponse which contains a statusCode property which you can access. 对于HTTP / HTTPS请求,它是一个NSHTTPURLResponse ,其中包含一个可以访问的statusCode属性。

let task = session.dataTaskWithRequest(request) {
        data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        let statusCode = httpResponse.statusCode
        // do whatever with the status code
    }

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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