Search code examples
iosnsarraynsdatansurlsessionswift2

How to parse NSData from NSURLSession to a NSArray


I'm doing a tutorial where they print the result of a NSURLSession as a string. But I would like to get an array out of it.

The URL I'm accessing has the following format: [24,68,69,70,71,72,73].

I think I do not fully understand how filling in a NSArray works because I cannot get this to work.

I thought simply creating a NSArray and putting in this data should do the trick, similarly as to how I can now print it:

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
     print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}

Output:

Optional([24,68,69,70,71,72,73])

I would also like to know why it encloses the output in "Optional()". Anyone who could clarify this for me?


Solution

  • If you get [24,68,69,70,71,72,73] from data, this data is a JSON array.

    You can use Foundation's NSJSONSerialization to decode the data and cast the result to either a Foundation object like an NSArray or to a Swift array of integers.

    Because it's Swift 2, NSJSONSerialization throws so you also have to use the do try catch syntax to handle errors.

    And Optional is a fundamental type in Swift. You should read the doc because it's very important to get this right. In a nutshell: an Optional is a type that contains either a value or nil. You have to "unwrap" an Optional to get the value. It's done with if let or guard let or ?? or several other ways.

    Here's a simple example of all this for your array (put it inside your NSURLSession task in replacement of your print command):

    do {
        if let myData = data, let myArray = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? [Int] {
            for number in myArray {
                print(number)
            }
        }
    } catch {
        print(error)
    }
    

    And if you have to use an NSArray instead of Swift array, just change the typecast:

    do {
        if let myData = data, let myArray = try NSJSONSerialization.JSONObjectWithData(myData, options: []) as? NSArray {
            for number in myArray {
                print(number)
            }
        }
    } catch {
        print(error)
    }