简体   繁体   中英

iOS: Almofire PUT and DELETE Call is not working with Params in Swift

I am trying to Put and Delete data through Almofire Library but facing issue regarding parameters. Params are missing, following are the error:

Response JSON data = {
    data = "<null>";
    issuccess = 0;
    msg = "{'car_id': [ErrorDetail(string='This field is required.', code='required')], 'car_brand_id': [ErrorDetail(string='This field is required.', code='required')], 'last_oil_change': [ErrorDetail(string='Date has wrong format. Use one of these formats instead: YYYY-MM-DD.', code='invalid')]} with error {  Custom error message.  }";
} 

I am using the following code:

let params : [String : String] = ["brand_model_id": String(car_model_id), "oil_brand_id": String(oil_brand_id), "car_mileage": edCurrentMilage.text!, "car_modelyear": edVehicleModelYear.text!, "last_oil_change": edLastOilChange.text!]


Alamofire.request(Constants.APIURL + Constants.APIPOSTCARDATA ,method:.put, parameters: params, encoding: JSONEncoding.default, headers: header).responseJSON { [self] response in
                guard response.result.isSuccess,
                    let value = response.result.value else {
                                print("Error while fetching tags: \(String(describing: response.result.error))")
                                self.hideIndicator()
            //                    self.btn_submit_outlet.isEnabled = true
                                // completion(nil)
                                return
                        }
                        print(value)
                        let json = JSON.init(value as! NSDictionary)
                        print(json)
                        let code = json["issuccess"].boolValue
                        if(code)
                        {
                            self.hideIndicator()
                            Commons.showAlert(title: "Alert", error: "Data has been added.", VC: self)
                        }
                        else
                        {
                            self.hideIndicator()
                            Commons.showAlert(title: String.localizedStringWithFormat(NSLocalizedString("Alert", comment: "")), error: String.localizedStringWithFormat(NSLocalizedString("Something went wrong.", comment: "")), VC: self)
                        }
                    }

Above mention code is used for the PUT call Please help. Thanks in advance.

It's not against you particularly, BUT , it's something that is lacking a lot in this kind of questions.

Usually, by reading output error, in our case the server response we might , and I insist on "might" , find the solution. But it's not always the case, sometimes error message is too generic, or pointing to the wrong direction. Here, error is saying about missing "car_id" param, but according to you it's not needed, so it's misleading (if we believe your saying).

Another usually good hint, is saying that "It's working on Android", "It's working in Postman", "It's working with a cURL command".

Usually, when this happen, I'm asking myself:
Why the author doesn't show the Postman, Android code, cURL command that would allow people knowing both tools/languages/platforms to spot a difference that could be the mistake.

Let's be honest, that would be easier, no? You might have quickly the right solution/fix, no? It's better than trying to guess battling agains the server response, no?

Now...

You are using Alamofire AND Postman. What if I told you that might be enough for you?

Quick trivia:
Did you know that Postman can generate code for the request?
It can even generate Swift Code for your request using URLSession ? It's not "beautiful", "swifty" Swift code, but it's enough to spot difference and find why it's working on Postman and not in your code.
It can also generate cURL command ? If you don't know about cURL a quick explanation would be "command line tool to make web request with params etc in Terminal.app/Bash/Shell, ie: it's basic and usually known by a lot of developers, so even if you only speak JavaScript, Java, etc, it's often like a "common language"
How? Even when I say that in comments, people don't even try to search for it... Let's find it with your favorite Search Engine, which should lead you to this tutorial/blog post . And tadaaa!
Did you know that AlamoFire can print request as cURL equivalent? It's stated here .

So in your case, what about asking Alamofire and Postman to generate cURL command and compare?
Then, you might want to change the parameters of the request, or even the parameters of the method request(_:method:parameters:encoding:headers:) .

Why I am saying this?
Because if you don't give enough informations, there will be a delay between someone asking for more info/details in comment and yourself responding to them. Also, different commenters will ask for different questions, since debugging is a skill and causes might be multiples, we might ask different things, and only one will be relevant in the end to your issue, but we can't guess which one until then.
Because spotting difference is easier and might attract quicker response.
Now that you know about POSTMAN and Alamofire and cURL, you might even find yourself the solution. Even quicker than making a question on SO! Be your own hero!
In the end, only an "attractive" question will have good answers, so give as much info as possible, don't hold them (parameters sent, equivalent android code, screenshot at least of the Postman, but know that you know about the cURL generation code). Of course, keep your private token etc, obfuscate them a little, but still, you might have watch enough TV shows/movies where holding info is bad for the main characters, why repeating that mistake here?

As the error message says: Date has wrong format. Use one of these formats instead: YYYY-MM-DD.

Please check "last_oil_change" field. The value is from edLastOilChange.text. Does edLastOilChange.text meet the required format?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM