Reputation: 275
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
Upvotes: 0
Views: 1776
Reputation: 14030
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)"
}
Upvotes: 4