ios - JSON Swift 填充 TableView 错误

标签 ios json swift tableview populate

我正在尝试在 TableView 中显示 JSON 数据,但收到一条错误消息:“无法将类型‘[String : JSON]’的值转换为预期的参数类型‘String’。有什么想法吗?提前致谢. 另外,我是否打算以正确的方式填充表格 View ?我正在使用 SwiftyJSON。

var TableData:Array< String > = Array < String >() 

    override func viewDidLoad() {
        super.viewDidLoad()

        splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible

        UINavigationBar.appearance().barTintColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)

        UINavigationBar.appearance().tintColor = UIColor.whiteColor()

        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

        //JSON

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

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in

            if error != nil {

                print(error)

            } else {

                if let _ = data {

                    do {

                        let jsonString = try NSString.init(contentsOfURL: url, encoding: NSUTF8StringEncoding)


                        // Create JSON object from data

                        let json = JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)

                        // Check if array for key "collection2" exists

                        if let collection2 = json["results"]["collection2"].array {

                            // Create JSON array from it and loop for each object

                            for (_, subJson):(String, JSON) in JSON(collection2) {

                                // Check if dictionary for key "Event" exists

                                if let event = subJson["Event"].dictionary {

                                    print(event)


                                }



                                // Check if string for key "Hasta" exists

                                if let hasta = subJson["Hasta"].string {

                                    print(hasta)


                                }

                                // Check if string for key "Location" exists

                                if let location = subJson["Location"].string {

                                    print(location)

                                }

                            }

                        }

                    } catch {
                        print("In catch block")
                    }

                }

            }

        }

        task.resume()

    }



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

    // MARK: - Table view data source

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

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


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

        cell.textLabel?.text = self.TableData[indexPath.row]

        return cell
    }
}

最佳答案

我修改了你的代码

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

var tableData = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible

    UINavigationBar.appearance().barTintColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)

    UINavigationBar.appearance().tintColor = UIColor.whiteColor()

    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]

    //JSON

    let url = "https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y"

    makeRequest("GET", api: url, params: nil, values: nil) { (dic) -> Void in
        if let resultsDic = dic.valueForKey("results") as? NSDictionary
        {
            if let collection2 = resultsDic.valueForKey("collection2") as? NSArray
            {
                //do the for loop and get values
            }
        }
    }



}

// MARK: - Table view data source

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

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


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

    cell.textLabel?.text = self.tableData [indexPath.row]

    return cell



}






typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>




func makeRequest(method : String , api : String , params : Dictionary<String , AnyObject>? , values : Dictionary<String , String>? , completionHandler : (NSDictionary->Void)?)
{

    var request = NSMutableURLRequest(URL: NSURL(string:api)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = method


    //    NSJSONSerialization.JSONObjectWithData(<#data: NSData#>, options: <#NSJSONReadingOptions#>, error: <#NSErrorPointer#>)


    // var err: NSError?
    if let myValues = values
    {
        for keyValue in myValues
        {
            request.addValue(keyValue.1, forHTTPHeaderField: keyValue.0)
        }
    }


    //var params = ["emailToFollow":self.user!.email, "follow" : follow.description] as Dictionary<String, String>


    if let myParams = params
    {
        //        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(myParams, options: nil, error: &err)
        do
        {
            try request.HTTPBody = NSJSONSerialization.dataWithJSONObject(myParams, options: [])

        }
        catch
        {
            print("error \n")
        }
    }


    //var httpRes = HttpPostREsult.FAIL



    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        //var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //        var err: NSError?

        do
        {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

            print("request sent \n")
            if let parseJSON = json
            {
                if let myComplitionHandler = completionHandler
                {
                    myComplitionHandler(parseJSON)
                }
            }
            else
            {
                // the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: \(jsonStr) \n")
            }

        }
        catch let error as NSError
        {
            print("error \(error.localizedDescription)")
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)

            print("error \(jsonStr)")
        }

    })
    task.resume()

}

变化: 1 - HttpRequest 函数,它向 url 发出请求并“返回”一个接受字典的 block ,这是一种更简洁的请求方式,它还有两个功能(您可以发送正文和 header ) 2 - 改变了你解析信息的方式

希望这有帮助! :D

关于ios - JSON Swift 填充 TableView 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324922/

相关文章:

javascript - 在reactJS中转换嵌套的json对象?

ios - 具有不同格式的 Swift Date 对象

html - 在 Mobile Safari 的 CSS 中使用 float right 时字体大小错误

javascript - 如何向 JSON 对象添加元素

ios - RestKit:映射 HTTP 响应始终为 null

json - Golang Godog REST API 测试失败

Swift CLI - $PATH 不完整

swift - 如何使用 XCode UI 测试清除文本字段中的值

ios - 当我的应用程序返回前台时调用我的 View 中的方法

ios - iOS8-iOS9设置提醒/闹钟