0

I am new to Swift and I'm trying to creat a mobile app for my woocommerce store. I created a product class with name, price and image src. I also created another productBank to store my product objects but I don't know how to populate it with JSON using Alamofire.

class Simpleproduct {

    var productName: String
    var productPrice: Int
    var ProductImage: String

    init(price: Int, name: String, image: String) {
        productName = name
        productPrice = price
        ProductImage = image
    }
}
class Productbank {

    var productlist = [Simpleproduct]()    

    init() {
        productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
        productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
        productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
        productlist.append(Simpleproduct(price: 5, name: "productname", image: "imagesrc"))
        // [...]
Olympiloutre
  • 2,268
  • 3
  • 28
  • 38
  • Possible duplicate of [Correctly Parsing JSON in Swift 3](https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3) – Olympiloutre Sep 12 '19 at 00:55
  • Are you retrieving products to display via an endpoint that necessitates using Alamofire, as I'm not seeing it in the code you've posted? You'll want to read up on the `Codable` protocol. If you're getting your data from an endpoint, I'd recommend converting your class to a `struct` that conforms to the `Codable` protocol. That will enable you to ditch the initializer (presuming you're getting a clean JSON back where Ints aren't something goofy like Strings, etc.) – Adrian Sep 12 '19 at 03:49

1 Answers1

0

Posting my answer again because it was deleted...

I recommend using AlamoFireObjectMapper, is a cool and easy to use library:

https://github.com/tristanhimmelman/AlamofireObjectMapper

your code will be something like this (you will receive the json automatically mapped to your object model):

The object Model

class EncuestaModel:Object, Mappable{
@objc dynamic var Id = 0
@objc dynamic var Name:String?
@objc dynamic var CreationDate:Date?
@objc dynamic var Status = 0
@objc dynamic var Default = false

    required convenience init?(map: Map) {
      self.init()
    }
}

and for the Alamofire request:

func getEncuestas(){
    let url = "yourApiUrl"

    Alamofire.request(url).responseObject {(response:DataResponse<LoginResultModel>) in
        if let result = response.result.value {
            //do your code here
        }
    }
}
Arturo Calvo
  • 46
  • 1
  • 13