简体   繁体   中英

how to insert nsdictionary value for all keys to uitableview swift 3.0

    //uitableoutletname
@IBOutlet weak var tableview: UITableView!
//overridefunction
override func viewDidLoad()
{
    super.viewDidLoad()
    let url = URL(string: "http://api.fixer.io/latest")
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject


                    //convert to nsdictionary
                    if let rates = myJson["rates"] as? NSDictionary
                    {
                        var myarry = [NSString]()
                        for (_,value) in rates
                        {

                            //thispart is giving error how cat it be resolved


                            myarry.append(value as! NSString)
                            self.tableview.beginUpdates()
                            self.tableview.insertRows(at: [IndexPath(row: myarry.count-1, section: 0)], with: .automatic)
                            self.tableview.endUpdates()
                        }
                    }
                }
                catch
                {

                }
            }
        }
    }
    task.resume()
}

I fetch data by json call converted it to nsdictionary and trying to insert into uitableview. It is giving some run time error. while i print variable value,and key using print comant it is working perfectly.

For me it looks like you're firing UI code from not-mine thread as URLSession will create it's own thread. Try to wrap your table view code with GCD:

DispatchQueue.main.async {
    self.tableview.beginUpdates()
    self.tableview.insertRows(at: [IndexPath(row: myarry.count-1, section: 0)], with: .automatic)
    self.tableview.endUpdates()
}

The dataTask is an async task, you should update the UI on the main thread. Also, let use Swift type intead of using NSDictionary and NSString .

if let rates = myJson["rates"] as? [String: Double] {

    DispatchQueue.main.async {

        for (_, value) in rates {

            self.myarry.append(String(value))
            self.tableview.beginUpdates()
            self.tableview.insertRows(at: [IndexPath(row: self.myarry.count-1, section: 0)], with: .automatic)
            self.tableview.endUpdates()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM