How to send shared model object as parameter of Alamofire mail method in Swift3?
I have a model class like this
class Example() {
var name:String?
var age:String?
var marks:String?
}
I am adding data to this model class
let example = Example()
example.name = "ABC"
example.age = "10"
example.marks = "10"
After that I went to JSON and then sent
Alamofire.request(URL, method:.post, parameters: example)
Alamofire doesn’t accept parameters only as acceptors like parameters = ["":"","",""]-->key value based
so I tried to convert the model to JSON, JSON to dictionary, although it didn’t accept it as a parameter problem. Exactly what I need is for the shared model object to be sent as a parameter to the post method in Alamofire like this:
let example = Example()
Alamofire.request(URL, method:.post, parameters: example)
source to share
Since the Alamofire API only accepts dictionaries, create a dictionary yourself!
Add a method to the model class named toJSON
:
func toJSON() -> [String: Any] {
return [
"name": name as Any,
"age": age as Any,
"marks": marks as Any
]
}
Then call this method when called 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
]
}
Using:
Alamofire.request(URL,
method:.put,
parameters:example.toJSON().dictionaryObject,
encoding:JSONEncoding.default,
headers :Defines.Api.Headers )
source to share
By far the best way is to bring your model into line with Encodable
. convert your model to JSON Data like this
let data = try! JSONEncoder.init().encode(example)
then use SwiftyJSON
to convert it back todictionary
let json = try! JSON.init(data: data) let dictionary = json.dictionaryObject
as Rob said you can also use JSONSerialization
if you are not already usingSwiftyJSON
let dictionary = try! JSONSerialization.jsonObject(with: data) as! [String: Any]
Then use dictionary
in your parameters
Also Alamofire now supports encoded parameters with
let urlRequest = JSONParameterEncoder.init().encode(example, into: urlRequest)
source to share