我创建了一个路由器来生成 URL 请求。
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
}
}
我期望的输出是:http://BASEURL/v1/aed?latitude=100&longitude=100
当我使用 Alamofire 发出带有附加参数的 GET 请求时,它工作正常:
Alamofire.request(.GET, "http://SERVER/v1/aeds", parameters: parameters).responseJSON { (response) -> Void in
print(response.result.value)
}
当我改用我的路由器时,输出没有按预期生成:
Alamofire.request(Router.GetAEDInRange(parameters)).responseJSON { (response) -> Void in
print(response.result.value)
}
当我打印 URL 字符串时,我得到:`http://SERVER/v1/aeds/ `` 我需要如何更换路由器?我以某种方式与参数组件作斗争。
最佳答案
改变这一行
let encoding = Alamofire.ParameterEncoding.JSON
为此:
let encoding = Alamofire.ParameterEncoding.URLEncodedInURL
要了解 Alamofire 中参数编码之间的区别,请查看 here .
关于swift - URL 请求的编码参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536772/