Swift Alamofire - POST request using parameters of NULL value

Viewed 2691

I have the Alamofire POST request in the following and the value of my parameter is optional. I would like to allow users to call this API to set the required parameter, even though it is NULL (it's kind of reset to empty default value).

Here's my request and the parameter status is an optional variable that it's expected to be accepting null value:

let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
let parameters: [String : Any] = ["status": status as Any]
                
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
    switch response.result {
    case .success:
        print("[Log] Update Status Success")
    case .failure(let error):
        print("[ERROR] UpdateStatus - \(error)")
                
        APIErrorHandler(response: response, error: error)
    }
}

However, I tried several times and it always returns some errors. I tried to be optional and I found that it isn't interpolated (i.e. it becomes "Optional(\"SOME_STATUS\")"). When I tried to force unwrap the string, those null values will cause fatal error. And also, I tried the methods of passing null as the value of the request parameter but it doesn't work anyway.

I don't understand how I should fix it, and could anyone help? Thanks a lot!

3 Answers

You can create the parameters dictionary then assign values to it. In this case they key would either have a value of not exist.

var parameters: [String : Any] = [:]
parameters["status"] = status

Don't pass null parameter you can check it has value the pass it

check this code

let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
var parameters: [String : Any]? = nil
if let status = status {
    parameters  = ["status": status]
}
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
        switch response.result {
        case .success:
            print("[Log] Update Status Success")
        case .failure(let error):
            print("[ERROR] UpdateStatus - \(error)")
                
        APIErrorHandler(response: response, error: error)
    }
}
Related