带有Swift 3的Alamofire 4.3,POST请求不适用于URL参数

时间:2017-01-23 09:04:51

标签: ios post swift3 alamofire

我正在尝试按如下方式发送帖子请求,我的路由器如下

enum ProfieRouter: URLRequestConvertible {

case loginUser(parameters: Parameters)
case resetPassword(parametrs: Parameters)

var method: HTTPMethod {

    switch self {

    case .loginUser:
        return .post

    case .resetPassword:
        return .post
    }
}

var path: String {

    switch self {
    case .loginUser:
        return "app/api.php?request=login"

    case .resetPassword:
        return "app/api.php?request=forgettenPassword"
    }
}

func asURLRequest() throws -> URLRequest {
    let BASEURL = "https://www.example.com/"
    let url = try BASEURL.asURL()
    var urlRequest = URLRequest(url: url.appendingPathComponent(path))
    urlRequest.httpMethod = method.rawValue


    switch self {

    case .loginUser(let parameters):
        urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)

    case .resetPassword(let parameters):
        urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
    }
    return urlRequest
}

}

这就是我从ViewController中调用它的方式,

@IBAction func signInButtonClicked(_ sender: Any) {

    let parameters: Parameters = [
        "email": "xxxxxx",
        "password": "xxxxxx"
    ]

    Alamofire.request(ProfieRouter.loginUser(parameters: parameters)).responseJSON{ response in


        switch response.result {
        case .success:
            print(response)

            break
        case .failure(let error):

            print(error)
        }

    }

}

但是我得到了如下错误,

responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

请注意,当我使用POSTMAN和Advanced REst Client进行检查时,我的API响应是有效的。我已经尝试了几个关于跟随错误的问题,但在我的情况下它们不起作用。

请有人指出我在这里犯的错误。 谢谢。

1 个答案:

答案 0 :(得分:1)

试试这个..

修改您的网络服务调用代码,如下所示:

// Add default headers if needed.(As per your web-service requirement)
let headers: HTTPHeaders = [
    "Accept": "text/html",
    "Content-Type" : "application/x-www-form-urlencoded"
]

 Alamofire.request("Your URL", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).validate().responseJSON { (response) in

  debugPrint(response)
}

希望它有所帮助。