0

I'm trying to display JSON data in a tableview and I'm receiving an error message: "Cannot convert value of type '[String : JSON]' to expected argument type 'String'. Any ideas? Thanks in advance. Also am I going about populating the tableview in the right way? I'm using 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
    }
}
1
  • What line did the error come? Commented Oct 25, 2015 at 0:45

1 Answer 1

1

I modified your code

    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()

}

Changes : 1 - HttpRequest function , which make a request to url and "returns" a block which accepts a dictionary , this is a cleaner way to do requests , it also have two features (you can send body and header ) 2 - changed the way you parsed the info

Hope this helped ! :D

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.