如何在 Swift 中的 Alamofire 中发送 body 参数?
Posted
技术标签:
【中文标题】如何在 Swift 中的 Alamofire 中发送 body 参数?【英文标题】:How to send body parameter in Alamofire in Swift? 【发布时间】:2019-04-18 06:07:34 【问题描述】:我有一个使用 BODY 参数的 api,像这样
"answers":["qid":2588,"value":["Free Society"],"qid":150,"value":["Closing of fSociety"]],"uniqid":"t4815694"
所以我所做的是,我创建了名为 SubmitAnswerModel
的数据模型,其中包含另一个名为 QuestionAnswersToSubmit
的数据模型
import Foundation
import ObjectMapper
import RealmSwift
class SubmitAnswerModel: Object
var answers = [QuestionAnswersToSubmit]()
@objc dynamic var uniqid: String?
override static func primaryKey() -> String
return "uniqid"
class QuestionAnswersToSubmit: Object
@objc dynamic var qid = 0
var value = [String]()
override static func primaryKey() -> String
return "qid"
所以这个对象扩展了RealmObject
,现在我需要为这个对象设置值并将其作为 api 中的 BODY 参数发送。我就是这样做的
func submitAnswerToApi()
guard let token = UserDefault().getLoginAccessTokenKey() else
print("No login token. Please relogin.")
return
let answersToSubmit = SubmitAnswerModel() //main model
let realm = try! Realm()
let savedExamResponse = realm.object(ofType: SavedExamResponse.self, forPrimaryKey: id)
answersToSubmit.uniqid = savedExamResponse?.uniqueId
var answerListToSubmit = [QuestionAnswersToSubmit]()
for item in (savedExamResponse?.questionAnswerList)!
let answerToSubmit = QuestionAnswersToSubmit()
answerToSubmit.qid = item.questionId
answerToSubmit.value = [item.selectedOption]
answerListToSubmit.append(answerToSubmit)
answersToSubmit.answers = answerListToSubmit
let urlString = UrlCollection.submitAnswerUrl + "uniqid=" + answersToSubmit.uniqid! + "&token=" + token
let param = answersToSubmit
let uniqidParam = answersToSubmit.uniqid
dump(param)
var request = URLRequest(url: URL(string: urlString)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if (!JSONSerialization.isValidJSONObject(answersToSubmit))
print("is not a valid json object")
//return
request.httpBody = try? JSONSerialization.data(withJSONObject: answersToSubmit)
Alamofire.request(request)
.responseJSON response in
switch response.result
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8)
print(responseString)
case .success(let responseObject):
print(responseObject)
所以现在的问题是,我收到了这个错误Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
。在 SWIFT 中传递 BODY 参数的正确方法是什么。任何帮助,将不胜感激。谢谢!
【问题讨论】:
【参考方案1】:您的 Json 格式可能有误,请参考以下问题: Invalid top-level type in JSON write'
顺便说一句,使用Alamofire
设置正文的首选方法是将Dictionary
传递给参数,然后将编码设置为URLEncoding.httpbody
,如下所示:
let parameters: Parameters = ["foo": "bar"]
Alamofire.request("https://someapi/post", parameters: parameters, encoding: URLEncoding.httpbody)
【讨论】:
以上是关于如何在 Swift 中的 Alamofire 中发送 body 参数?的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView 中的 Alamofire + Swift
如何将 alamofire 返回 json 解析为 Swift 中的字符串数组?
如何在 Swift 中从 alamofire 中提取数据? [复制]
如何在 Swift 3 中使用 Alamofire 4 解析这个 json?