gpt4 book ai didi

json - 如何在 Swift 的 Alamofire 中发送 body 参数?

转载 作者:行者123 更新时间:2023-11-28 07:28:19 24 4
gpt4 key购买 nike

我有一个使用 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)
}
}


}

所以现在的问题是,我收到此错误 Termating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON 写入'。在 SWIFT 中传递 BODY 参数的正确方法是什么?任何帮助,将不胜感激。谢谢!

最佳答案

你的Json格式可能不对,请引用这个问题: Invalid top-level type in JSON write'

顺便说一句,使用 Alamofire 设置 body 的首选方法是将 Dictionary 传递给参数,然后将编码设置为 URLEncoding.httpbody ,像这样:

let parameters: Parameters = ["foo": "bar"]

Alamofire.request("https://someapi/post", parameters: parameters, encoding: URLEncoding.httpbody)

关于json - 如何在 Swift 的 Alamofire 中发送 body 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55739987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com