I'm currently working on the currency rates app. I have a main
ViewController which has a UILabel which presents parsed rate for selected currencies. Also, there is a button which is used for changing one of the currency rates in order to get a new rate (second
ViewController is presented with N tableView cells).
I have some troubles with transferring data of new selected value to the main
ViewController. When I select a new rate, I get this error for UILabel:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I guess I know how to fix it - create a variable inside main
and set its value inside second
viewcontroller, but i don't know how do it properly. Here is my code. Thanks in advance.
class MainVC: UITableViewController {
var convertedValue: String = ""
// some stuff
func parseCurrency(top: String) {
let URL_Exchange = URL(string: "MY URL\(top)")!
let task = URLSession.shared.dataTask(with: URL_Exchange) {(data, response, error) in
guard let data = data else { return }
let queue = DispatchQueue(label: "result")
queue.async {
let JSON = String(data: data, encoding: .utf8)
let jsonData = JSON!.data(using: .utf8)!
let result: Rates = try! JSONDecoder().decode(Rates.self, from: jsonData)
let currencies = result.conversion_rates?.dictionary
var doubleVar:Double = 0
for item in currencies! {
if (item.key == self.BottomCurrency.sublabel) {
doubleVar = item.value as! Double
}
}
// this value is the text to print inside "Result" Label
let mult = Double(round(10000*doubleVar * self.InputText)/10000)
self.convertedValue = String(mult)
DispatchQueue.main.async {
if self.convertedValue == "0" {
self.Result.text = String(0)
} else {
// Here I get an error
self.Result.text = self.formatNumber(num: Double(self.convertedValue))
}
}
}
}
task.resume()
}
Code for second
VC:
class SecondVC: UITableViewController {
private var temp: Int = 0
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isBeingDismissed {
// updating temp value...
let vc = storyboard!.instantiateViewController(withIdentifier: "main") as! MainVC
vc.parseCurrency(top: Currencies[temp].short)
// or to call vc.convertedValue = something
// vc.parseCurrency(...)
}
}