使用Alamofire.request和URLRequestConvertible发出POST请求

时间:2016-01-03 05:12:09

标签: ios iphone swift cocoa-touch alamofire

以下是我的URLRequestConvertible

的代码
enum Router: URLRequestConvertible {
    static let baseURLString = "http://example.com/"

    case LoginRequest(String, String)
    case SignUpRequest(String)
    case ForgotPasswordRequest(String)

    var URLRequest: NSMutableURLRequest {

        let result: (path: String, method: Method, parameters: [String: AnyObject]) = {
            switch self {
            case .LoginRequest(let userName, let password):
                let params = [userNameKey: userName, passwordKey: password]
                return ("/AppUsers/login", .POST, params)
            case .SignUpRequest(let profile):
                let params = [fullNameKey: profile]
                return ("/AppUsers/add", .POST, params)
            case .ForgotPasswordRequest(let emailId):
                let params = [userNameKey: emailId]
                return ("/AppUsers/forgot_password", .POST, params)
            }
        }()

        let URL = NSURL(string: Router.baseURLString)
        let request = NSMutableURLRequest(URL: URL!.URLByAppendingPathComponent(result.path))
        let encoding = ParameterEncoding.URL

        request.URLRequest.HTTPMethod = result.method.rawValue
        return encoding.encode(request, parameters: result.parameters).0
    }
}

现在,我有以下要求正常工作:

 Alamofire.request(.POST, CommunicationService.Router.LoginRequest(txtUsername.text!, txtPassword.text!).URLRequest, parameters: ["email_id": txtUsername.text!, "password": txtPassword.text!], encoding: ParameterEncoding.JSON, headers: nil).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (response) -> Void in
        print(response)
    }

但是我想使用URLRequestConvertible来传递POST请求的参数。让我知道使用以下API的POST请求的最佳方式是什么:

 request(.POST, CommunicationService.Router.LoginRequest(txtUsername.text!, txtPassword.text!).URLRequest).responseJSON(completionHandler: { (response) -> Void in
        print(response)
        })

实际上,上面的代码提供了无效的响应,并显示以下错误消息

FAILURE:Error Domain = NSCocoaErrorDomain Code = 3840“字符0周围的值无效。” UserInfo = {NSDebugDescription =字符0周围的值无效。}

使用request(Method,URLStringConvertible)方法生成的请求有什么问题?

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您需要使用request方法的其他形式。

let loginRequest = CommunicationService.Router.LoginRequest(username,  password).URLRequest

Alamofire.request(loginRequest).responseJSON { in
    print(response)
}

否则,您只使用NSURLRequest创建的原始Router中的URLString。