我有变量,我想把它们放在 url 中发布
一些变量可以是波斯语或英语字符
当角色是英语时一切都很好
但是当我使用波斯字符时,alamofire 响应无效的 url
代码是。
let headers : Dictionary = [ "Content-Type":"application/json" ];
let request = Product_Rename() . request.newName = string .
request.productId = UInt(_Data[deletIndex].ProductId!)
Alamofire.request("http://example.com/api/product/rename?productId=\(_Data[deletIndex].ProductId!)&newName=\(string)&AUTHID=\(authID!)",
method: .put,
headers: headers)
.validate(statusCode: 200..<300)
.responseString(completionHandler: {response in
})
.responseJSON(completionHandler: {response in
switch response.result{
case .success:
if let data = response.data, let utf8Text = String(data:data,encoding:.utf8){
let x = Product_Rename_Response(json:utf8Text)
if x.success == true {
self._Data[self.deletIndex].Name = string
self._ProductTable.reloadData()
}else{
self.dismiss(animated: true, completion: nil)
}
}
case .failure(let error):
print(error)
break
}
})
最佳答案
您必须从 URL 中转义特殊字符。
request.productId = UInt(_Data[deletIndex].ProductId!)
let url = "http://example.com/api/product/rename?productId=\(_Data[deletIndex].ProductId!)&newName=\(string)&AUTHID=\(authID!)"
if let encodedUrl = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) {
Alamofire.request(encodedUrl,
method: .put,
headers: headers)
.validate(statusCode: 200..<300)
.responseString(completionHandler: {response in
})
// use the data
}
addingPercentEncoding(withAllowedCharacters:)
方法会将字符编码为 percent encoding (例如 https://example.com/foo.php?text=bar%20baz
,其中 %20
代表一个空格)。
关于swift - URL 中的波斯字符(使用 Alamofire),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741688/