为URL请求编码参数

时间:2016-02-21 13:32:57

标签: swift alamofire nsurlrequest urlrequest

我创建了一个路由器来生成URL请求。

.odbc.ini

我期望的输出是:enum Router: URLRequestConvertible { static let baseURLString = "SERVERIP" case GetAEDInRange(String) // match URLRequest routes to Alamofire methods var URLRequest: NSMutableURLRequest { var method: Alamofire.Method { switch self { case .GetAEDInRange: return .GET } } // The output contains the path and parameters like ("aeds", newAED) let result: (path: String, parameters: [String: AnyObject]?) = { switch self { case .GetAEDInRange(let parameters): return ("aeds", parameters) }() // Generate URL Request let URL = NSURL(string: Router.baseURLString)! // Append the path components from the result print(result.path) let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(result.path)) // Create URLRequest inclunding the encoded parameters let encoding = Alamofire.ParameterEncoding.JSON let (encodedRequest, _) = encoding.encode(URLRequest, parameters: result.parameters) encodedRequest.HTTPMethod = method.rawValue return encodedRequest } }

当我使用Alamofire发出附加参数的GET请求时,它可以正常工作:

http://BASEURL/v1/aed?latitude=100&longitude=100

当我使用我的路由器时,输出不会按预期生成:

    Alamofire.request(.GET, "http://SERVER/v1/aeds", parameters: parameters).responseJSON { (response) -> Void in
        print(response.result.value)
    }

当我打印URL String时,我得到:`http://SERVER/v1/aeds/`` 我如何更换路由器?我以某种方式与参数组件斗争。

2 个答案:

答案 0 :(得分:2)

更改此行

let encoding = Alamofire.ParameterEncoding.JSON

到此:

let encoding = Alamofire.ParameterEncoding.URLEncodedInURL

要了解Alamofire中参数编码之间的区别,请查看here

答案 1 :(得分:1)

Swift3 'Alamofire','〜> 4.0'

    let parameters: [String: Any] = [
            "parameter1" : data1,
            "parameter2" : data2
        ]

Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .queryString))