0

我想在 swift 2.2 中使用 Alamofire for i 代码发送带有 .POST 请求的 Json 对象,如下所示:

let dictionary: [String: AnyObject] = [
            "cUserEmail" : "abc@abc.com",
            "cUserPassword" : "abc",
            "cDeviceId" : "asdf"
        ]

        let url = NSURL(string: endPoint)

        let request = NSMutableURLRequest(URL:url!)
        request.HTTPMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)

        Alamofire.request(request)
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .Failure(let error):
                    print(error)
                case .Success(let responseObject):
                    print(responseObject)
                }
        }

但上面提到的代码不起作用。以前,在objective-c中我使用了如下代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.securityPolicy.allowInvalidCertificates = YES;
 [manager POST:URLString parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

简而言之,我想要使用 Alamofire 的 swift 2.2 的等效代码。

4

2 回答 2

0

尝试对这样的 body 使用空选项:

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: [])
于 2016-04-28T07:50:36.773 回答
0

我通过以下方法找到了我的解决方案,
希望它对你有用......

let dictionary: [String: AnyObject] = [
            "cUserEmail" : "abc@abc.com",
            "cUserPassword" : "abc",
            "cDeviceId" : "asdf"
        ]

let request2 = Alamofire.request(.POST, "http://localhost:8080/api/v1/register", parameters: dictionary, encoding: .JSON)
request2.validate()
request2.responseJSON(completionHandler: { (let response) in

    let data = response.data!
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
        print ( "json is \(json)")

    } catch {
        print("error serializing JSON: \(error)")

        self.showAlert("Error :\(error)")
    }
})
于 2016-05-27T13:56:20.497 回答