我有变量,我想把它们放在url中发布
一些变量可以是波斯语或英文字符
当角色是英语时,一切都很好
但是当我使用波斯语时,alamofire会回复无效的网址
代码是。
let headers:Dictionary = [ “内容类型”:“应用/ JSON” ];
let request = Product_Rename()。 request.newName = string。
request.productId = UInt(_Data[deletIndex].ProductId!)
Alamofire.request("http://www.axprint.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
}
})
答案 0 :(得分:1)
您必须从URL中转义特殊字符。
request.productId = UInt(_Data[deletIndex].ProductId!)
let url = "http://www.axprint.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
表示空格。)