如何在 Alamofire 中使用相同的 API 函数 .PUT 请求更新 JSON
Posted
技术标签:
【中文标题】如何在 Alamofire 中使用相同的 API 函数 .PUT 请求更新 JSON【英文标题】:How to update JSON using same API Function .PUT request in Alamofire 【发布时间】:2018-09-24 03:10:01 【问题描述】:我已经收集了关于我之前的SO Question 关于如何在 ALamofire 中使用 PUT 请求的解决方案,并使用下面的解决方案。
func updateParticipant(updateType: UpdateParticipantType,
participantID: String,
completionHandler: @escaping ( (_ result:Any?, _ error:Error?) -> Void))
let updateParticipantURL = URL(string: "\(REGISTER_PARTICIPANT_URL)/\(participantID)")
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"accept": "application/json"
]
let parameters: [String : Any] = [
"registered_flag": true,
"registration_type": 1
// "out_flag": true
]
Alamofire.request(updateParticipantURL!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON (response) in
print(response)
switch response.result
case .success:
print("Done")
if let success = response.result.value as? [[String : Any]]
completionHandler(success, nil)
case .failure(let error):
completionHandler(nil, error)
我现在的问题是,如果活动参与者使用下面的json
结帐,我该如何更新记录。
"out_flag": true
使用相同的 API 函数 updateParticipant
因为当我尝试插入时
let parameters: [String : Any] = [
"registered_flag": true,
"registration_type": 1
"out_flag": true
]
参与者在注册后会自动签出。这是错误的,因为在实际事件中,参与者应该先注册并签到。它检查事件是否完成。希望你能帮助我解决这个问题。我是 swift 新手,对我第一次遇到的事情感到很困惑。非常感谢。
【问题讨论】:
什么是updateType
?您目前没有使用它。但我认为您可以处理添加/删除out_flag
参数。
@Kamran 。 . updateType
用于枚举 UpdateParticipantType
、enum UpdateParticipantType: String case checkIn = "Check In" case checkOut = "Check Out"
。我将如何构建代码?
【参考方案1】:
基于updateType
,可以处理如下参数,
首先将let
更改为var
,以便您可以根据updateType
添加/删除参数。并用下面的通用属性初始化parameters
,
var parameters: [String : Any] = ["registered_flag": true, "registration_type": 1]
现在您可以根据updateType
添加可选参数。
if updateType == .checkOut
parameters["out_flag"] = true
同样,如果您必须发送一些checkIn
相关参数,您也可以以同样的方式处理,
if updateType == .checkIn
parameters["someCheckInParameterName"] = true
【讨论】:
非常感谢。我可以在updateParticipants
函数中添加可选参数吗?
是的,您需要更新parameters
内部updateParticipants
中的构造
你好,我想我在调试的错误轨道FAILURE: responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(409))
出现在我的控制台中
我想通了。感谢您的帮助。 :D以上是关于如何在 Alamofire 中使用相同的 API 函数 .PUT 请求更新 JSON的主要内容,如果未能解决你的问题,请参考以下文章
iOS/IBM Cloud/Swift:使用 AlamoFire 发布到 Watson API
如何在 Alamofire API 请求的主体中发送嵌套对象?
api请求失败时如何在swift alamofire中使用responsedecodable解析错误