Hey CodeCrew!
I need your help trying to apply what I’ve learned here without any success…
My app should be able to use json to transfer data on an online database when given a product code and return the details found.
I have created my model as follow:
struct Product() {
var code:Int?
var productName:String?
var brand:String?
}
I have created my controller like this:
import Foundation
import Alamofire
import SwiftyJSON
class RetrieveProductFromWebsiteModel {
var productDirectory = Product()
func retriveProduct(productSku: Int, completion: @escaping (Product) -> Void) {
let urlString = "https://example.com/file.json"
DispatchQueue.main.async {
let request = AF.request(urlString)
request.responseJSON { (response) in
guard let _ = response.data else {
return
}
let json = try? JSON(data: response.data!)
self.productDirectory.code = json?["code"].int
self.productDirectory.productName = json?["product_name"].string
self.productDirectory.brandName = json?["brand-name"].string
}
completion(self.productDirectory)
}
}
}
And in my View Controller:
- UIButton
- UITextField
import UIKit
class ViewController: UIViewController {
var model = RetrieveProductFromWebsiteModel()
var product:Product?
@IBOutlet weak var jsonTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showJson(_ sender: Any) {
let productCode = 123456 // Note: this code will be variable in next integration
DispatchQueue.main.async {
self.model.retriveProduct(productSku: productCode, completion: { (product) in
print(product.code)
print(product.productName)
self.jsonTextView.text = "Name is " + (product.productName ?? "") + "\n"
})
}
}
}
My problem is that "Name is " gets printed (and “nil / nil” in the console) the first time I click the button, the second time it is finally printing the correct values.
So I presume I am not using the DispatchQueue.main.async as I should… but how?
Many thanks in advance!