简体   繁体   中英

How to set JSON output into UILabel in Swift 4.0?

I'm working on an app built in Swift 4.0 (Xcode Beta 9) that will pull in Bitcoin values from the Bitstamp API (this part is working) and output the value in a label. Where I'm stuck is getting the output of this call into my label.

The value prints out here:

let btcValues = try
JSONDecoder().decode(BitcoinResponse.self, from: data)
print("$" + btcValues.last)

Complete code in my ViewController.swift file:

import UIKit

struct BitcoinResponse: Decodable {
    let high: String
    let last: String
    let timestamp: String
    let bid: String
    let vwap: String
    let volume: String
    let low: String
    let ask: String
    let open: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "https://www.bitstamp.net/api/v2/ticker/btcusd/"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) {
            (data, response, err) in
            guard let data = data else { return }

            do {
                let btcValues = try
                    JSONDecoder().decode(BitcoinResponse.self, from: data)
                print("$" + btcValues.last)
                                }
            catch let jsonErr {
                print("Error serializing json:", jsonErr)
            }

        }.resume()

    }
    @IBOutlet weak var btcValue: UILabel!
    //output goes here
}

My outlet btcValue is referenced here:

@IBOutlet weak var btcValue: UILabel!
//output goes here

I would rather not use an external library such as SwiftyJSON to accomplish this (as I've gotten 99% of the way there without it).

Thank you

Just assign the value to the label's text property (from the main thread):

let btcValues = try JSONDecoder().decode(BitcoinResponse.self, from: data)
DispatchQueue.main.async {
    self.btcValue.text = "$\(btcValues.last)"
}

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