Taco Taco - 1 year ago 303
iOS Question

How to use Alamofire with an array in a Json dictionary?

To perform a POST request with Alamofire, I would like to create a Json dictionary with an array (with elements of type AnyObject) as a dictionary value.

However, when I define the dictionary as

[String: AnyObject]
and try to save an array it results in a

var fields = [String: AnyObject]()
fields["key1"] = [1,2,3] // But this could also be an array of type Array<AnyObject>
fields["key2"] = "Foo"

"["key1": <_TtCs21_SwiftDeferredNSArray 0x7fdfe9f0c2d0>(\n1,\n2,\n3\n)\n, "key2": Foo]\n"

When the dictionary values are defined of type
the output is what I expect to be:

var fields = [String: Any]()
fields["key1"] = [1,2,3]
fields["key2"] = "Foo"

"["key1": [1, 2, 3], "key2": "Foo"]\n"

Unfortunately, Alamofire seems not to accept dictionary values of type

Cannot convert value of type '[String : Any]?' to expected argument type '[String : AnyObject]?'

How should I use Alamofire with POST requests with Swift arrays?

Answer Source

Although I don't know whether the SwiftDeferredNSArray output is a bug in Swift, in Swift 3 the dictionary value must be Any by default.

Since this is also updated in the Swift 3 version of Alamofire, the SwiftDeferredNSArray does not occur anymore and the problem is solved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download