Using Swift to get url content using session.dataTaskWithRequest () - data is not converted to NSString

Why is my code below successfully returning data, with status code 200, but unable to convert the returned NSData to NSString?

var session: NSURLSession

func init() {
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    session = NSURLSession(configuration: config)
}

func getStatic(url:NSURL) {
    let request = NSMutableURLRequest(URL: url)
    let dataTask = session.dataTaskWithRequest(request) {(data, response, error) in
        if error != nil {
            // handle error
        } else {
            // data has a length of 2523 - the contents at the url
            if let httpRes = response as? NSHTTPURLResponse {
                 // httpRes is 200
                 let html = NSString(data:data, encoding:NSUTF8StringEncoding)
                 // **** html is nil ****
             }
        }
    }
    dataTask.resume()
}

      

+3


source to share


2 answers


The code is really correct.

The url I was trying to download had non-UTF8 characters and so the error I ran with NSString(data:data, encoding:NSUTF8StringEncoding)

failed.



Removing all UTF8 characters fixed the problem. Or choosing an appropriate encoding NSISOLatin1StringEncoding

worked for my content as well.

+4


source


It looks like everything should be fine, at least for me. I'm just doing Swift, but I made my apps (not sure if this is the correct name) changed slightly as shown below. Have you tried converting data to NSString before your string if let httpRes = response as? NSHTTPURLResponse

? Perhaps the data variable doesn't actually contain html. I have code written almost exactly the same, with the changes below that I can successfully convert the data to an NSString.

let dataTask = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    if error != nil {
        // handle error
    } else {
        if let httpRes = response as? NSHTTPURLResponse {
             let html = NSString(data:data, encoding:NSUTF8StringEncoding)
         }
    }
})

      



Hope it helps.

0


source







All Articles