0

以下のようにAlamofire for iコードを使用して、swift 2.2で.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

以下の方法を実行して解決策を見つけました
...

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 に答える
0

そのようなボディに空のオプションを使用してみてください:

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