2015-10-25 31 views
0

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

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 
    } 
} 
+0

错误是从哪里来的? – anhtu

回答

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

希望这有助于! :D