簡體   English   中英

如何使用Alamofire Swift 4以JSON編碼方式傳遞數據

[英]How to pass data in JSON Encoding with Alamofire Swift 4

無法弄清楚如何使用Alamofire .post方法將日期傳遞到服務器。 我必須像這樣形成JSON主體:

{
    "title": "My Title",
    "locations": [
        {
            "location": "locationID"
        }
        ],
}

我被困在“位置”屬性上。 可能必須是具有一個location屬性(是字符串類型)的對象數組。 目前,我的代碼是:

@IBAction func createEvent(_ sender: Any) {
    let parameters: Parameters = [
        "title": Event.title ?? nil,
        "locations":   //What have I wright here?
    ]

    Alamofire.request(requestURL,
                      method: .post,
                      parameters: parameters,
                      encoding: JSONEncoding.default,
                      headers: headers).responseJSON {response in

                        switch response.result {
                        case .success:
                            print(response)

                        }
                        case .failure(let error):

                            print(error)
                        }
    }
}

請幫忙。

你可以試試

let parameters: Parameters = [
    "title": Event.title ?? nil,
    "locations": [["location":"idherrr"]]
]

如果您的API請求接受特定的字符串格式,則您需要使用DateFormatter將字符串格式的Date轉換為String;否則,如果您接受Date對象,則可以傳遞但Date對象,但這可能是不可能的。 因此,請嘗試使用由服務器參數決定的以字符串格式轉換日期的第一個選項。

或者,如果可能,請在服務器上共享請求參數類型支持。

你可以嘗試

let parameters: Parameters = [
    "title": Event.title ?? nil,
    "locations": [dictionary]]
]

暫無
暫無

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

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