查询Alamofire中的参数

时间:2017-08-22 09:05:09

标签: ios swift rest request alamofire

在我的iOS应用程序中,我使用Alamofire 4并希望通过查询参数向后端发送请求。但是Alamofire转换了“?”在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,但它没有用。

1 个答案:

答案 0 :(得分:6)

您需要创建网址字符串并设置URLEncoding,如

let urlwithPercent = yourURlString.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
var urlRequest = URLRequest(url: URL(string: urlwithPercent))

这里yourURlString是一个完整的URL作为字符串(http://blahblahblah/mobile-proxy/authorizations%3FphoneNumber=+555555555&userID=agent