baryon5
baryon5

Reputation: 55

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?

Upvotes: 0

Views: 477

Answers (2)

rakeshbs
rakeshbs

Reputation: 24572

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

Upvotes: 1

rastersize
rastersize

Reputation: 487

NSString can be type casted to a Swift String, it’s even done automatically for you. So the following should be enough in your case:

if let res = NSString(data: data, encoding: NSUTF8StringEncoding) {
    handler(res)
} else {
    // handle that the data wasn’t convertible to a string.
}

(I added the if let part as it’s generally a bad idea to force-unwrap optionals.)


However the reason you’re getting the error however is because you’re defining the res constant to be of type String. Then you try to initialize it with an NSString object which the type system won’t like.

Upvotes: 0

Related Questions