简体   繁体   中英

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. 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. So I can't simply check if the return dict is empty.

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. For HTTP/HTTPS requests it's an NSHTTPURLResponse which contains a statusCode property which you can access.

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
    }

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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