使用Alamofire 3.0 +

时间:2016-04-27 16:04:34

标签: json post alamofire xcode7.3 swift2.2

我想在swift 2.2中使用Alamofire for i code发送带有.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等效代码。

2 个答案:

答案 0 :(得分:0)

尝试对身体使用空选项:

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: [])

答案 1 :(得分: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)")
    }
})