I am trying to use a NSURLSession
to pull some data from espn, but I can't seem to get it to work. It prints only nil
.
I've tested this method with another page on their website and it worked, but I can't get it to work with the one in the code. Here is the code in question:
var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
print(urlContent)
I've also tried changing the encoding type which didn't work either. The data it's printing looks like it's UTF 8 format, so I didn't think that would work but felt I should try.
I feel like I've run out of ideas to work.
Edit : Should have specified more, print(data)
prints out what I expected, encoded data, but print(urlContent)
prints nil
.
Here's the full example that works
var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data, encoding: NSASCIIStringEncoding) as NSString!
print(urlContent)
}
})
task.resume()
}
Looks like the right encoding here is NSASCIIStringEncoding
not NSUTF8StringEncoding
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With