NSDictionnary

时间:2015-07-20 14:18:37

标签: ios swift

我正在开发一个iOS项目,我想知道如何使用url从我的数据库中获取数据。

我尝试了很多代码,但没有任何作用。

我的代码的这部分似乎有些问题:

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

如果我NSArray println它会给我NSArray,但如果我需要将其放到NSDictionnary,则该变量为空并且不显示任何内容。

如何获取NSArray值并将其放在UITableViewCell中,以及这不能与as? NSDictionnary一起使用?

2 个答案:

答案 0 :(得分:1)

你也不应断言它是一个阵列。 NSJSONSerialization.JSONObjectWithData:options:error:返回的值取决于JSON。它可以是数组或字典,具体取决于文档的根目录。

在你的具体情况下,你显然期待一本字典,但它不是;它是一个阵列。

我建议你仔细看看你的JSON和JSON解析教程。您可能需要包含更多错误处理和内省,以使其在现实世界中可靠地运行。

答案 1 :(得分:0)

尝试这样做:

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

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

然后打印(json)以查看您回来的对象

这是我用来发出请求的一些代码:

    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关于提出请求的答案

这是一个简单的cellForRowAtIndexPath方法,它从数组中填充tableViewCells:

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
}

在viewDidLoad中使用此self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

相关问题