Alamofire 4, Swift 3 and building a json body

对着背影说爱祢 提交于 2020-01-02 04:11:29

问题


{"title":"exampleTitle","hashTags":[{"name":"tag1"},{"name":"tag2"}],"uploadFiles":
[{"fileBytes":"seriesOfBytes\n","filename":"upload.txt"}]}

That is my desired body I want to send to the backend.

I'm using Swift 3.0 and Alamofire 4 and i have multiple questions.

first, How do i correctly create a body which contains values and arrays of values?

My approach is:

let para:NSMutableDictionary = NSMutableDictionary()
para.setValue("exampleTitle", forKey: "title")
let jsonData = try! JSONSerialization.data(withJSONObject: para, options: .init(rawValue: 0))
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as! String
print(jsonString)

which gives me

{"title":"exampleTitle"}

second, my alamofire .post request looks like the following and is not working:

Alamofire.request(postURL, method: .post, parameters: jsonString, encoding: JSONEncoding.default)
        .responseJSON { response in
            debugPrint(response)
    }

i get the error message: extra argument 'method' in call. If i instead of jsonString use a string of the type

 var jsonString: [String : Any]

it does work, but i do not know how to put the body into this type.

summary looking for help (example would be the best) on how to create the body, and how to send it via Alamofire 4 and swift 3 to my backend.


回答1:


You need to pass parameter as [String:Any] dictionary, so create one dictionary as your passing JSON like this.

let params = [ 
                "title":"exampleTitle",
                "hashTags": [["name":"tag1"],["name":"tag2"]],
                "uploadFiles":[["fileBytes":"seriesOfBytes\n","filename":"upload.txt"]]
             ]

Now pass this params as parameter in Alamofire request.

Alamofire.request(postURL, method: .post, parameters: params, encoding: JSONEncoding.default)
    .responseJSON { response in
        debugPrint(response)
}


来源:https://stackoverflow.com/questions/40702845/alamofire-4-swift-3-and-building-a-json-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!