swift - URL 中的波斯字符(使用 Alamofire)

标签 swift post request alamofire

我有变量,我想把它们放在 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/

相关文章:

java - 使用java发送文件以形成帖子

symfony - 如何设置请求 symfony 的内容?

javascript - Axios 与请求

ios - FBSDKGraphRequest 如何获取个人资料封面照片?

java - 来自 Java 的 CloudFlare(成员(member))post 请求产生 403 错误

ios - 重新加载具有图像的 UICollectionViewCell

javascript - 用 php 在 ajax 中发帖让我得到 undefined index

javascript - 使用Javascript(Ajax)将大量小请求传递给PHP(登录mysql)

swift - 带有 NsurlConnection 的 UIViewActivityIndi​​cator 不会快速停止动画

ios - 工具栏中间的 Admob 横幅