When a user loads my app the first time it crashes because it unwraps a optional nil value, but the next time it loads perfectly
I first thought this was due to the notification being pushed after the networking request, I tried pushing the notification just after realm.add(object, update: true) but this didn't seem to be the problem.
this is from my Networking class:
func updateBitcoinData(bitcoinJSON: JSON){
print("Parsing the JSON")
let receivedData = Rates()
receivedData.btcUSD = bitcoinJSON["bpi"]["USD"]["rate"].string!
receivedData.btcGBP = bitcoinJSON["bpi"]["GBP"]["rate"].string!
receivedData.btcEUR = bitcoinJSON["bpi"]["EUR"]["rate"].string!
receivedData.usdSymbol = bitcoinJSON["bpi"]["USD"]["symbol"].string!.html2String
receivedData.gbpSymbol = bitcoinJSON["bpi"]["GBP"]["symbol"].string!.html2String
receivedData.eurSymbol = bitcoinJSON["bpi"]["EUR"]["symbol"].string!.html2String
receivedData.chartName = bitcoinJSON["chartName"].string!
receivedData.timeUpdated = receivedData.convertUTCDateToLocalDate(dateToConvert: bitcoinJSON["time"]["updated"].string!)
do {
try realm.write {
realm.add(receivedData, update: true)
DispatchQueue.main.async {
NotificationCenter.default.post(name: .ReceivedBitcoinData, object: nil)
}
}
} catch {
print("Error saving rates, \(error)")
}
This is what I do in my ViewController class:
override func viewWillAppear(_ animated: Bool) {
loadRates()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.bitcoinDataReceived(_:)), name: NSNotification.Name(rawValue: "ReceivedBitcoinData"), object: nil)
}
@objc func bitcoinDataReceived(_ notification: Notification) {
updateBitcoinData()
}
@objc func updateBitcoinData() {
bitcoinPriceLabel.text = rates!.usdSymbol + rates!.btcUSD
chartName.text = rates?.chartName
timeUpdated.text = rates?.timeUpdated
}
The error throws in this line upon first load, it crashes, but as I mentioned on second load it works fine
bitcoinPriceLabel.text = rates!.usdSymbol + rates!.btcUSD