【问题标题】:Query params in Alamofire在 Alamofire 中查询参数
【发布时间】:2018-01-30 11:37:48
【问题描述】:

在我的 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,但它不起作用。

【问题讨论】:

    标签: ios swift rest request alamofire


    【解决方案1】:

    你需要创建你的 url 字符串并设置 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      相关资源
      最近更新 更多