Search code examples
iosswiftalamofireput

How to update JSON using same API Function .PUT request in Alamofire


I already gathered solution regarding my previous SO Question regarding How to use PUT request in ALamofire with this solution below.

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)
            }
        }
    }

My problem now is how can I update the record if the event participant will check out using the json below.

 {     
  "out_flag": true
  }

using the same API Function updateParticipant because when I tried to insert as

let parameters: [String : Any] = [
        "registered_flag": true,
        "registration_type": 1
        "out_flag": true
    ]

The participant is automatically checked out, once registered. Which is wrong because in the actual Event, the participant should register first and check in. It check outs if the event is finished. Hope you could help me regarding this issue. I am new in swift and quite puzzled in things I encountered for the first time. Thank you so much.


Solution

  • Base on the updateType, you can handle the parameters as below,

    First change let to var so that you can add/remove a parameter based on the updateType. And initialize parameters with the common attributes as below,

    var parameters: [String : Any] = ["registered_flag": true, "registration_type": 1]
    

    now you can add optional parameters based on the updateType.

    if updateType == .checkOut {
        parameters["out_flag"] = true
    }
    

    Similarly if you have to send some checkIn related parameter you can handle that also in the same way,

    if updateType == .checkIn {
        parameters["someCheckInParameterName"] = true
    }