簡體   English   中英

帶有 SwiftyJSON 參數的 Alamofire 請求

[英]Alamofire request with SwiftyJSON parameters

我想知道如何將 SwiftyJSON 數組放入 Alamofire 請求的參數中。

實際上我使用此代碼(Swift 3)來設置請求的參數:

let params = ["customObjects": customObjects.map({$0.toJSON()})]

...但是如果我嘗試啟動請求,這會引發異常:

uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

“customObjects”是我的自定義模型類的數組。

如果您需要更多信息,請告訴我。

您可以將 SwiftyJSON 對象(此處稱為yourJSON )轉換為如下參數:

let parameters : Parameters = yourJSON.dictionaryObject ?? [:]

然后你可以在 Alamofire 請求中使用它,如下所示:

Alamofire.request("https://yourURL.com/somePath", method: .post, parameters: parameters, encoding:  JSONEncoding.default, headers: nil).responseJSON { response in
   // ... do whatever you would like with the response 
}

我自己找到了解決方案:

let params = ["customObjects": customObjects.map({$0.toDictionary()})]

這里是我的 CustomObject 中的 toDictionary() 函數:

func toDictionary() -> [String: Any] {
    let dict: [String: Any] = [
        "exampleKey": "exampleValue",
        "exampleKey2": "exampleValue2"
    ]

    return dict
}

我想這是因為您可以使用encoding: JSONEncoding.default設置 Alamofire encoding: JSONEncoding.default

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM