补丁与 Alamofire (swift 2.3)
PATCH with Alamofire (swift 2.3)
我有问题,我尝试使用 Alamofire 使用 PATCH 方法更新,但没有反映任何更改。
我认为其中一个我犯了一些错误。
这是我的代码:
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")
}
}
希望大家能帮帮我,而且我查了资料也不多。
此致。
尝试使用 .PUT
而不是 .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.
此外,请检查服务器从您的应用接收请求是否正确。检查 URL、参数、格式和调用类型。如果一切正确,请检查响应数据。
您需要使用自定义编码并将您的参数作为原始字符串发送到正文中
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)
})
终于使用了自定义编码
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")
}
}
Swift 4 和 Alamofire 4.6 示例:
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
}
}
}
我有问题,我尝试使用 Alamofire 使用 PATCH 方法更新,但没有反映任何更改。
我认为其中一个我犯了一些错误。
这是我的代码:
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")
}
}
希望大家能帮帮我,而且我查了资料也不多。
此致。
尝试使用 .PUT
而不是 .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.
此外,请检查服务器从您的应用接收请求是否正确。检查 URL、参数、格式和调用类型。如果一切正确,请检查响应数据。
您需要使用自定义编码并将您的参数作为原始字符串发送到正文中
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)
})
终于使用了自定义编码
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")
}
}
Swift 4 和 Alamofire 4.6 示例:
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
}
}
}