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

问题描述 投票:1回答:1

我有一个消耗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,现在我需要为这个对象设置值并将其作为BODY参数发送到api中。我是这样做的

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参数的正确方法是什么。任何帮助,将不胜感激。谢谢!

json swift realm alamofire
1个回答
0
投票

你的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)

© www.soinside.com 2019 - 2024. All rights reserved.