Search code examples
iosposthttp-headersswiftnsurlrequest

NSURLResponse does not have a member named allHeaderFields


I'm making a POST request to an API and I get the response successfully in Swift. Below is my code.

private 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!, response: NSURLResponse!, error: NSError!) -> Void in

        if error {
            println("Error Occurred: \(error.localizedDescription)")
        } else {
            println("\(response.allHeaderFields)") // Error
        }
    })
    dataTask.resume()
}

I'm trying to dump the header fields using allHeaderFields but I get an error saying NSURLResponse does not have a member named allHeaderFields. But it does have it!

There must be something wrong with the syntax or the way I'm calling it. Can anyone please tell me how to correct this?

Thank you.


Solution

  • Elaborating on what Yogesh said...!

    Try to cast the NSURLRespones into a NSHTTPURLResponse using "as", because I'm betting the NSURLResponse is actually a NSHTTPURLResponse, or I'm betting that is possible.

    Here is what I mean:

    private 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()
    }