Below is the code of my 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
}
}
Now, I have below request which is working fine:
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)
}
But I want to make the use of URLRequestConvertible for Parameter passing for POST request. Let me know what is the best way for POST request using below API:
request(.POST, CommunicationService.Router.LoginRequest(txtUsername.text!, txtPassword.text!).URLRequest).responseJSON(completionHandler: { (response) -> Void in
print(response)
})
Actually, above code is giving Invalid response with below error message
FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
What's wrong with the request generated using request(Method, URLStringConvertible) method?
Can any one help me?
You need to use the other form of the request
method.
let loginRequest = CommunicationService.Router.LoginRequest(username, password).URLRequest
Alamofire.request(loginRequest).responseJSON { in
print(response)
}
Otherwise you are only using the URLString from the original NSURLRequest
being created by the Router
.