0

I just started a new IOS app and I've some issue with Json (I read everything I could on this website an other, but I didn't manage to make it work properly...

I've a json file and I want to change labels with the content of it.

This is my json file:

{
    "cours": [{
        "name": "Terrain blanc",
        "nbre": "4",
        "image": "urlimage",
        "prix": "595",
        "desc": "hhhhh"
    }, {
        "name": "Terrain blanc",
        "nbre": "6",
        "image": "urlimage",
        "prix": "415",
        "desc": "hhhhh"
    }, {
        "name": "Terrain bleu",
        "nbre": "4",
        "image": "urlimage",
        "prix": "595",
        "desc": "hhhhh"
    }]
}

and this is my code:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var cours1Lbl: UILabel!
    @IBOutlet weak var nbreEnfants1Lbl: UILabel!
    @IBOutlet weak var description1: UILabel!
    @IBOutlet weak var prix1Lbl: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let url = URL(string: "http://www.boisdelacambre.be/ios/json/cours.json")
        let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
            if let content = data {
                do {
                    self.cours1Lbl.text = "test"
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    let listeCours: NSArray = myJson["cours"] as! NSArray
                    let nameCours = listeCours[0] as! [String:AnyObject]
                    let nomDuCours:String = (nameCours["name"] as! String?)!
                    print(nomDuCours)
                    self.cours1Lbl.text = "\(nomDuCours)"

                } catch
                {
                    print("erreur Json")
                }
            }

        }
        task.resume()
    }
}

I can print nomDuCours but I can't change self.cours1Lbl.text (the initial value stays)

Any help will be highly appreciated...

1 Answers1

1

Try changing the label's text on the main thread like so:

DispatchQueue.main.sync
{
    self.cours1Lbl.text = "\(nomDuCours)"
}

Edit:

Also, don't forget to add 'App Transport Security Settings' to your info.plist to allow the request. If you don't, then data would be nil, and your code inside the request completion won't execute:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Keep in mind that allowing all loads can cause your app to be rejected from the App Store, but for development purposes..

Alvaro Roman
  • 46
  • 1
  • 4