1

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
OldTimes
  • 300
  • 1
  • 3
  • 16

1 Answers1

0

This is happening because you are trying to access data before being saved into Realm database. You can use guard to avoid crash like:

@objc func updateBitcoinData() {
    guard let rates = rates else{return}
    bitcoinPriceLabel.text = rates.usdSymbol + rates.btcUSD
    chartName.text = rates.chartName
    timeUpdated.text = rates.timeUpdated
}
nikksindia
  • 1,147
  • 1
  • 10
  • 18
  • The problem still persists and seems to transfer to my pickerview delegate method, which displays the currencie once it is selected by the user, the same error is thrown – OldTimes Dec 28 '18 at 14:31
  • you need to use 'guard' there as well, just to be sure that a particular value exists when you are trying to access it and avoid forcecast as much as you can – nikksindia Dec 28 '18 at 14:33
  • Ok I tried that but now it doen't display anything, the data doesn't even seem to save to my realm update: it saves, but it still doesn't display anything – OldTimes Dec 28 '18 at 14:35
  • try to debug why your data is not saving/fetching from Realm but I guess that is out of scope for this question – nikksindia Dec 28 '18 at 14:45