Mapping MySQL Data In Swift

Viewed 38

I am setting up my swift code to use MySQL database. Up until this point I have only used Firebase/Firestore. I have installed the OHMySQL library via CocoaPods. I am confused as to how the Object Mapping works. I have added an example of how I did it using Firestore.

func fetchProductData(){
        
        let db = Firestore.firestore()
        
        db.collection("Products").getDocuments { (snap, err) in
            
            guard let productData = snap else{return}
            
            self.products = productData.documents.compactMap({ (doc) -> Product? in
                
                let id = doc.documentID
                let name = doc.get("product_name") as? String ?? "No product name"
                let image = doc.get("product_image") as? String ?? "No product image"
                let details = doc.get("product_details") as? String ?? "No product details"
                let website = doc.get("product_website") as? String ?? "No product website"
                let stock = doc.get("product_stock") as! Int
                let uid = doc.get("product_uid") as? String ?? "No uid"
                
                return Product(id: id, product_name: name, product_image: image, product_details: details, product_website: website, product_stock: stock, product_uid: uid)
            })
            
            self.filteredProduct = self.products
        }
    }

I believe that as I am using Swift, I cannot use fundamental number types (Int, Double), only NSNumber.

What would this mapping be like using a MySQL database?

1 Answers

This is an example of how to get the product name data:

func fetchProductData() {
    
    let url = URL(string: "INSERT YOUR URL HERE")!
    
    //2.
    URLSession.shared.dataTask(with: url) {(data, response, error) in
        
        do {
            if let todoData = data {
                //3.
                let decodedData = try JSONDecoder().decode([Product].self, from: todoData)
                DispatchQueue.main.async {
                    self.products = decodedData
                    
                    self.filteredProduct = decodedData
                    
                }
                
                //Fetching name of product
                decodedData.forEach { course in print(course.product_name)}
                
            } else {
                print("No Data")
            }
            
        } catch {
            print(error)
        }
        
    }
    .resume()

}
Related