How to send total model object as a parameter of Alamofire post method in Swift3?

前端 未结 2 1503
-上瘾入骨i
-上瘾入骨i 2021-02-09 05:51

I have a model class like this

class Example() {
  var name:String?
  var age:String?
  var marks:String? 
}

I\'m adding data to that model cla

2条回答
  •  佛祖请我去吃肉
    2021-02-09 06:24

    The best way so far is to make your model conform to Encodable then convert you model into json Data like so

    let data = try! JSONEncoder.init().encode(example)
    

    then use SwiftyJSON to convert it back to dictionary

    let json = try! JSON.init(data: data)
    let dictionary = json.dictionaryObject
    

    as Rob said you can also use JSONSerialization if you are not already using SwiftyJSON

    let dictionary = try! JSONSerialization.jsonObject(with: data) as! [String: Any]
    

    Then use the dictionary in your parameters

    Also Alamofire now supports Encodable parameters with

    let urlRequest = JSONParameterEncoder.init().encode(example, into: urlRequest)
    

提交回复
热议问题