Getting Header Response in Swift

倖福魔咒の 提交于 2019-12-13 11:42:26

问题


I am following this answer for making HTTP calls in my swift project. How to make an HTTP request in Swift?

and following is the code I am using to make a synchronous call

let urlPath: String = "http://apiserver.com/api/login/?username=asdf&password=asdf"
            var url: NSURL = NSURL(string: urlPath)!
            var request1: NSURLRequest = NSURLRequest(URL: url)

            var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil

            var error: NSErrorPointer = nil
            var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
            var err: NSError

            println("response -- \(response)")
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

            println("Synchronous \(jsonResult)")

is here anyone who can help me to get HTTP Header Response or status code by using this code? please


回答1:


Try this:

 func getData(url: NSURL) {
    let config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session: NSURLSession = NSURLSession(configuration: config)

    let dataTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data: NSData!, urlResponse: NSURLResponse!, error: NSError!) -> Void in

        if let httpUrlResponse = urlResponse as? NSHTTPURLResponse
        {
            if error {
                println("Error Occurred: \(error.localizedDescription)")
            } else {
                println("\(httpUrlResponse.allHeaderFields)") // Error
            }
        }
        })

       dataTask.resume()
    }



回答2:


Per your code in the original question, have you tried this?

let urlPath: String = "http://apiserver.com/api/login/?username=asdf&password=asdf"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)

var response: NSURLResponse? = nil

var error: NSError? = nil
var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error:&error)!
var err: NSError

println("response -- \(response)")
if let response = response as? NSHTTPURLResponse {
    if response.statusCode == 200 {
        print("Success")
    }
}
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

println("Synchronous \(jsonResult)")


来源:https://stackoverflow.com/questions/32140587/getting-header-response-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!