Luckio
Luckio

Reputation: 127

PATCH with Alamofire (swift 2.3)

I have a problem, i try to update with PATCH method using Alamofire, but no changes are reflected.

I Think in one of those I am making some mistake.

This is my code:

    Alamofire.request(.PATCH, url, parameters: ["op": "replace", "path": "/IsVacinated", "value": true], encoding: .JSON)
        .responseJSON { response in
            Utils.endRequest(progressView)
            if let data = response.data {
                let json = JSON(data: data)
                if json != nil {
                    self.navigationController?.popViewControllerAnimated(true)
                    print(json)
                }
                else {
                    print("nil json")
                }
            }
            else {
                print("nil data")
            }
    }

I hope you can help me, and that I have searched and not much information.

Best regards.

Upvotes: 3

Views: 4258

Answers (3)

Denis Kutlubaev
Denis Kutlubaev

Reputation: 16124

Swift 4 and Alamofire 4.6 example:

struct CustomPATCHEncoding: ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        let mutableRequest = try! URLEncoding().encode(urlRequest, with: parameters) as? NSMutableURLRequest

        do {
            let jsonData = try JSONSerialization.data(withJSONObject: parameters!, options: .prettyPrinted)
            mutableRequest?.httpBody = jsonData
        } catch {
            print(error.localizedDescription)
        }

        return mutableRequest! as URLRequest
    }
}

func updateProfile() {
    let phoneString = self.phone.value
    let formattedPhoneString = phoneString.digits
    var parameters : Parameters = ["email": self.email.value,
                                   "first_name": self.firstName.value,
                                   "last_name": self.lastName.value,
                                   "id": self.id.value]

    if formattedPhoneString.count > 0 {
        parameters["phone"] = formattedPhoneString
    }

    Alamofire.request(APPURL.Profile,
                      method: .patch,
                      parameters: parameters,
                      encoding: CustomPATCHEncoding(),
                      headers:APIManager.headers())
        .debugLog()
        .responseJSON { response in

            switch response.result {
            case .success(let JSON):
                print("Success with JSON: \(JSON)")
                break
            case .failure(let error):
                print("Request failed with error: \(error.localizedDescription)")
                break
            }
        }
}

Upvotes: 1

Pedro Rothen Cuevas
Pedro Rothen Cuevas

Reputation: 66

You need to use a custom encoding and send your parameters as a raw string in the body

let enconding: ParameterEncoding = .Custom({convertible, params in
                let mutableRequest = convertible.URLRequest.copy() as? NSMutableURLRequest
                mutableRequest?.HTTPBody = "[{\"op\" : \"replace\", \"path\" : \"/IsVacinated\", \"value\":true"}]".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                if let mutableRequest = mutableRequest {
                    return (mutableRequest, nil)
                }
                let error = NSError(domain: "Custom", code: -1, userInfo: nil)
                return (convertible.URLRequest, error)
            })

Finally using the custom encoding

Alamofire.request(.PATCH, url, parameters: [:], encoding: encoding)
        .responseJSON { response in
            Utils.endRequest(progressView)
            if let data = response.data {
                let json = JSON(data: data)
                if json != nil {
                    self.navigationController?.popViewControllerAnimated(true)
                    print(json)
                }
                else {
                    print("nil json")
                }
            }
            else {
                print("nil data")
            }
    }

Upvotes: 4

Kumar
Kumar

Reputation: 1942

Try using .PUT instead of .PATCH

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

Also, Check is server receiving request from your app is correct or not. Check for URL, Parameters, format and call type. If all things is correct, check for response data.

Upvotes: 0

Related Questions