Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Website Data Using Swift

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.

like image 335
Alex Avatar asked Dec 25 '22 19:12

Alex


1 Answers

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 NSASCIIStringEncodingnot NSUTF8StringEncoding.

like image 163
Jure Avatar answered Jan 13 '23 12:01

Jure