简体   繁体   English

JSON TableView Swift 错误

[英]JSON TableView Swift Error

I'm trying to populate a tableview with this JSON URL.我正在尝试使用此 JSON URL 填充 tableview。 I validated the URL, and it works fine.我验证了 URL,它工作正常。 My code is at fault.我的代码有问题。 I have a 'Repository.swift' file with a class inside.我有一个“Repository.swift”文件,里面有一个类。 Here's my code: I can't resolve the issue.这是我的代码: 我无法解决问题。

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
}

You need to add try catch您需要添加 try catch

I fixed your code我修复了你的代码

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
        }

    }
}

Kindly try it.请尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM