为什么我不能将JSON数据添加到我的iOS代码中?

时间:2016-11-19 05:28:44

标签: ios json

我是iOS开发的新手,并且即将从API导入的JSON数据创建存储桶列表。但是,运行以下代码后,应用程序始终崩溃,无法显示API中的列表。谁可以帮我这个事?我试过了大约3个小时。

enter image description here

import Foundation
import UIKit

class PeopleViewController: UITableViewController {
    var people = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://swapi.co/api/people/")
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: {
            data, response, error in
            print("in here")
            print(data)

            do {
                // Try converting the JSON object to "Foundation Types" (NSDictionary, NSArray, NSString, etc.)
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {

                    if let results = jsonResult["results"] {
                        // coercing the results object as an NSArray and then storing that in resultsArray
                        let resultsArray = results as! NSArray
                        print(resultsArray.count)
                        print(resultsArray.firstObject)

                        print("JSONRESULTARRAY", resultsArray)
                        for character in resultsArray{
                            if let name = character["name"]{
                                print("CHARACTER NAME", name!)
                                self.people.append(String(name))
                            }
                        }

                       dispatch_async(dispatch_get_main_queue(), {
                            self.tableView.reloadData()
                        })
                    }
                }
                } catch {
                print("Something went wrong")
            }
        })
        task.resume()
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // return the count of people
        return people.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Create a generic cell
        let cell = UITableViewCell()
        // set the default cell label to the corresponding element in the people array
        cell.textLabel?.text = people[indexPath.row]
        // return the cell so that it can be rendered
        return cell
    }
}

0 个答案:

没有答案