How to set JSON output into UILabel in Swift 4.0?

梦想的初衷 提交于 2019-12-11 15:37:29

问题


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


回答1:


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)"
}


来源:https://stackoverflow.com/questions/45990349/how-to-set-json-output-into-uilabel-in-swift-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!