JSON TableView Swift错误

时间:2015-10-23 00:14:39

标签: ios json swift tableview

我正在尝试使用此JSON URL填充tableview。我验证了URL,它工作正常。我的代码有问题。我有一个里面有类的'Repository.swift'文件。这是我的代码:我无法解决问题。

var repositories = [Repository]()

override func viewDidLoad() {
    super.viewDidLoad()

    let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!

    if let JSONData = NSData(contentsOfURL: reposURL) {
        if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
            if let reposArray = json["items"] as? [NSDictionary] {
                for item in reposArray {
                    repositories.append(Repository(json: item))
                }
            }
        }
    }
}

func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return self.repositories.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    cell.textLabel?.text = repositories[indexPath.row].Event
    cell.detailTextLabel?.text = repositories[indexPath.row].Hasta

    return cell
}

1 个答案:

答案 0 :(得分:0)

您需要添加try catch

我修复了你的代码

override func viewDidLoad() {
    super.viewDidLoad()

    let reposURL = NSURL(string: "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!

    if let JSONData = NSData(contentsOfURL: reposURL) {
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .MutableContainers)
            if let reposArray = json["items"] as? [NSDictionary] {

                for item in reposArray {

                    // repositories.append(Repository(json: item))


                }
            }
        }catch {
        //do whatever
        }

    }
}

请试一试。