在我的iOS应用程序中,我使用Alamofire 4,并希望用查询参数将请求发送到后端。但阿拉莫菲把“?”到url查询(http://blahblahblah/mobile-proxy/authorizations%3FphoneNumber=+555555555&userID=agent)中的%3F,我从后端得到404错误。我读到了关于URLEncoding的内容,但是我找不到任何方法可以将其与URLRequest一起使用,因为我将自定义路由器枚举文件与URLRequest一起使用。这是我的路由器文件的一部分:
func asURLRequest() throws -> URLRequest {
let url = try Router.baseUrl.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .authorizations:
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue(getHeaderCredentials().operationID, forHTTPHeaderField: Constants.operationID)
urlRequest.setValue(getHeaderCredentials().appCode, forHTTPHeaderField: Constants.appCode)
case .startAuthentication, .startContractOperation:
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue(getHeaderCredentials().appCode, forHTTPHeaderField: Constants.appCode)
case .operationAllowance:
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
default:
break
}
switch self {
case .authorizations:
urlRequest = try Alamofire.URLEncoding.queryString.encode(urlRequest, with: nil)
default:
break
}
return urlRequest
}
我尝试了Alamofire.URLEncoding.queryString.encode,但它不起作用。
最佳答案
您需要创建url的字符串并将URLEncoding设置为
let urlwithPercent = yourURlString.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
var urlRequest = URLRequest(url: URL(string: urlwithPercent))
这里的url string是一个完整的url字符串(http://blahblahblah/mobile-proxy/authorizations%3FphoneNumber=+555555555&userID=agent)