rJK
rJK

Reputation: 3

Passing JSON data to a label in Swift

I'm new to coding and have a (hopefully easy) question.

I am trying to display JSON data as a label using swift. I'm not getting any errors but nothing is showing up using the following code:

  let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, ErrorType) -> Void in

        if let urlContent = data {

            do {

            let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)

                print(jsonResult)

                let text = jsonResult as? String

                self.textLabel.text = text

            } catch {

                print("JSON serialization failed")

            }

        }

    }

    task.resume()

Thanks!

Upvotes: 0

Views: 4110

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Just update your label into main thread this way:

dispatch_async(dispatch_get_main_queue()) {
    self.textLabel.text = text
}

UPDATE:

You can use SwiftyJSON for that.

And below is your working code with that library:

import UIKit

class ViewController: UIViewController {

    var dict = NSDictionary()

    @IBOutlet weak var authorLbl: UILabel!
    @IBOutlet weak var quoteLbl: UILabel!

    override func viewDidLoad() {

        super.viewDidLoad()

        let urlString = "http://api.theysaidso.com/qod.json"

        if let url = NSURL(string: urlString) {

            if let data = try? NSData(contentsOfURL: url, options: []) {

                let json = JSON(data: data)

                print(json)

                let auther = json["contents"]["quotes"][0]["author"].stringValue

                let quote = json["contents"]["quotes"][0]["quote"].stringValue

                authorLbl.text = auther

                quoteLbl.text = quote

            }

        }

    }
}

Upvotes: 3

Related Questions