-2

I'm working on an iOS project and I want to know how can I get data from my database using the url.

I have tried many codes but nothing works.

I seem to have some problem with this part of my code :

let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &err) as? NSArray

If I put NSArray the println it gives me the NSArray but if i need to put this to NSDictionnary the variable is empty and nothing appears.

How can I take the NSArray value and put it in a UITableViewCell and how this doesn't work with as? NSDictionnary ?

Rachel Harvey
  • 1,719
  • 2
  • 15
  • 23

2 Answers2

1

You shouldn't be asserting that it's an array either. The value returned by NSJSONSerialization.JSONObjectWithData:options:error: depends on the JSON. It could be an array or a dictionary, depending on what the root of your document is.

In your specific case, you're obviously expecting a dictionary but it isn't; it's an array.

I suggest you take a closer look at your JSON and a JSON parsing tutorial. You'll probably need to include a lot more error handling and introspection to make it work reliably in the real world.

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
0

Try doing this:

//replace
let jsonData:NSArray = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &err) as? NSArray

//with
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

and then print(json) to see what kind of object you're getting back

Here's some code I use to make a get request:

    let url = NSURL(string: urlString)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler:{
        (data, response, error) in
        if error != nil {
          //Handle error, just for testing I do this:
            print(error!.localizedDescription)
        } else {
            let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
            print(json)
          //use data from json, if it's a dictionary, you can loop through and add objects to an array
        }
    })
    task!.resume()

Here's an answer about making requests

And here's a simple cellForRowAtIndexPath method, which fills tableViewCells from an array:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell")
    let text = self.tableContents[indexPath.row] as! String
//tableContents is just the array from which you're getting what's going in your tableView, and should be declared outside of your methods
    cell.textLabel?.text = text
    return cell
}

With this self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") in viewDidLoad

Community
  • 1
  • 1
Rachel Harvey
  • 1,719
  • 2
  • 15
  • 23