Search code examples
xcodestringswiftnsstringnsdata

Converting the NSData returned from an HTTP request in Swift to a String


I have some code that makes an HTTP request, then calls a function with the data, response, and error results. This function then tries to call a function, handler, that takes a Swift String as its sole argument. I have tried to convert the NSData object (data) returned from the HTTP request to an NSString, and then from there to a Swift String, but XCode gives an error saying '(String) -> $T2' is not identical to 'String' when I try to call my function (handler) on that String (res).

    let res: String = NSString(data: data, encoding: NSUTF8StringEncoding)!
    handler(res)

Any ideas on how to fix this error?


Solution

  • You syntax for the closure is wrong.
    Try changing handler: (String) to handler: (String) -> ()

    func do_request(url: String, data: String?, handler: (String) -> ()) {
        // Your code
        if let res: String = NSString(data: data, encoding: NSUTF8StringEncoding)
        {
             handler(res)
        } 
    }
    

    Read this for more information : https://www.codefellows.org/blog/writing-completion-blocks-with-closures-in-swift