Search code examples
arraysjsonswiftdispatch

Parsing JSON array to label


I am trying to parse the JSON below (actual data is 20x the format listed)

{
message = "";
result =     (
            {
        Ask = "4.8e-05";
        BaseVolume = "32.61025363";
        Bid = "4.695e-05";
        Created = "2017-06-06T01:22:35.727";
        High = "5.44e-05";
        Last = "4.69e-05";
        Low = "4.683e-05";
        MarketName = "BTC-1ST";
        OpenBuyOrders = 293;
        OpenSellOrders = 4186;
        PrevDay = "4.76e-05";
        TimeStamp = "2018-02-20T00:00:31.863";
        Volume = "662575.93818332";
    },

This is the code that I have right now. It successfully prints the value "Last" to the console but when I incorporate the Dispatch.Queue, I get a Thread 1: signal SIGBRT not printing the value to the label.

let myJson = try JSONSerialization.jsonObject(with: content) as! [String:Any]

if let info = myJson["result"] as! [[String:Any]]?
{
    for i in 0..<20 {
        if i == 1
        {
            if let dict = info[i] as? [String:Any]
            {
                if let price = dict["Last"]
                {
                    print(price)
                    //DispatchQueue.main.async
                    //{
                    //   self.label1.text =  price as String
                    //}
                }
            }
        }

Any help is greatly appreciated!


Solution

  • Most likely your self.label1 outlet isn't connected. Fix that connection.

    You should also update the if let that gets the value for the "Last" key as follows:

    if let price = dict["Last"] as? String{
        print(price)
        DispatchQueue.main.async {
           self.label1.text =  price
        }
    }
    

    There is some other cleanup you can do as well:

    if let myJson = try JSONSerialization.jsonObject(with: content) as? [String:Any] {
        if let info = myJson["result"] as? [[String:Any]] {
            for (index, dict) in info.enumerated() {
                if index == 1 {
                    if let price = dict["Last"] as? String {
                        print(price)
                        DispatchQueue.main.async {
                           self.label1.text =  price
                        }
                    } // else no "Last" or not a String
                }
            }
        } // else "result" doesn't contain expected array of dictionary        
    } // else content isn't a valid JSON dictionary
    

    Avoid all of those forced casts. Especially avoid force casting to an optional.