2

我想使用 CRUD 示例作为基础向 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)
     }

任何帮助将不胜感激!

4

1 回答 1

4

您可以mutableURLRequest通过调用encodeAlamofireParameterEncoding实例上的方法来应用参数。如果它是一个标准的 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
}
于 2014-12-20T03:31:17.587 回答