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

前端 未结 2 1499
-上瘾入骨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:41

    Since the Alamofire API is only accepting dictionaries, create a dictionary yourself!

    Add a method in the model class called toJSON:

    func toJSON() -> [String: Any] {
        return [
            "name": name as Any,
            "age": age as Any,
            "marks": marks as Any
        ]
    }
    

    Then call this method when calling request:

    Alamofire.request(URL, 
        method:.put, 
        parameters:example.toJSON(), 
        encoding:JSONEncoding.default, 
        headers :Defines.Api.Headers )
    

    Alternatively, use SwiftyJSON:

    func toJSON() -> JSON {
        return [
            "name": name as Any,
            "age": age as Any,
            "marks": marks as Any
        ]
    }
    

    Usage:

    Alamofire.request(URL, 
        method:.put, 
        parameters:example.toJSON().dictionaryObject, 
        encoding:JSONEncoding.default, 
        headers :Defines.Api.Headers )
    

提交回复
热议问题