我想使用CRUD示例作为Base向Alamofire请求添加一些POST参数。我无法发送参数。
enum Router: URLRequestConvertible {
static var baseURLString: String = NSUserDefaults.standardUserDefaults().objectForKey("url") as String!
case GetForms()
case Login(String, String)
var method: Alamofire.Method {
switch self {
case .GetForms:
return .GET
case .Login:
return .POST
default:
return .GET
}
}
var path: String {
switch self {
case .GetForms():
return "getforms"
case .Login(let email, let password):
return "login"
default:
return ""
}
}
var URLRequest: NSURLRequest {
let URL = NSURL(string: Router.baseURLString)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
switch self {
case .GetForms():
let token: String = NSUserDefaults.standardUserDefaults().objectForKey("apikey") as String!
mutableURLRequest.HTTPMethod = method.rawValue
mutableURLRequest.setValue(token, forHTTPHeaderField: "Authorization")
return mutableURLRequest
case .Login(_, let parameters):
// HERE I WANT TO ADD THE 2 POST Paramers from the Login Function
return mutableURLRequest
default:
return mutableURLRequest
}
}
}
但这不起作用。我试图改为示例代码,但我真的不明白如何添加简单的2 Post参数。它应该像我使用它作为一个简单的请求时一样。像:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["email": "admin", "password": "password"])
.response { (_, _, _, error) in
println(error)
}
任何帮助都会受到极大的关注!
答案 0 :(得分:4)
您可以通过在Alamofire mutableURLRequest
实例上调用encode
方法将参数应用于ParameterEncoding
。如果它是标准的POST请求,您将要使用URL
案例:
switch self {
case .GetForms():
// ...
case .Login(let email, let password):
// do any URL request setup first
mutableURLRequest.HTTPMethod = method.rawValue
// set up parameters
let parameters = ["email": email, "password": password]
// return first element of tuple from encode
return ParameterEncoding.URL.encode(mutableURLRequest, parameters).0
default:
return mutableURLRequest
}