JSON Swift填充tableview错误

时间:2015-10-25 00:42:50

标签: ios json swift tableview populate

我正在尝试在tableview中显示JSON数据,并且我收到一条错误消息:“无法将类型'[String:JSON]'的值转换为预期的参数类型'String'。任何想法?提前感谢我还要以正确的方式填充tableview吗?我正在使用SwiftyJSON。

Page:
  extensions:
    - PageExtension

1 个答案:

答案 0 :(得分:1)

我修改了你的代码

    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发出请求并“返回”一个接受字典的块,这是一种更简洁的方式来做请求,它还有两个功能(你可以发送正文和标题) 2 - 改变了解析信息的方式

希望这有帮助! :D