Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 2.0 : Cannot POST with JSON from IOS

Ever since upgrading my IOS code to use AFNetworking version 2.0 instead of 1.x, I cannot do an HTTP Post any more with JSON parameters.

I suspect it is because my HTTP request header is not "application/json" but I have tried to do that and it still does not work.

This is my test code for trying to POST by JSON:

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                email, @"email",
                                password, @"password",
                                nil];

[[OTApiClient sharedInstance] POST:@"login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"result: %@", responseObject);

        Boolean response = [[responseObject valueForKey:@"success"] boolValue];
        if(response == TRUE) {
            //ok, success
            NSLog(@"success");

            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Successfully logged in" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];


        } else {
            NSLog(@"Not successful");

            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"The email or password is incorrect." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [alert show];
        }


        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@ ,  for operation: %@", error, operation);


        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"There is a problem connecting to the server, please try again soon." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];


        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    }];

});

and I keep getting this error :

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa  error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xca80730 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} ,  for operation: <AFHTTPRequestOperation: 0xca6bee0, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0xca76040> { URL: http://1.2.3.4:9000/api/login }, response: <NSHTTPURLResponse: 0xc963d60> { URL: http://1.2.3.4:9000/error404 } { status code: 404, headers {
"Content-Length" = 1809;
"Content-Type" = "text/html; charset=utf-8";

} }>

I am very sure that the server is up and accessible because all other GET calls work properly.

I have checked the updated documentation for AFNetworking 2.0 and it seems like what I have is the right way to do a JSON POST

Please let me know if I missed anything

Thanks IS

like image 899
user1805458 Avatar asked Dec 04 '13 20:12

user1805458


People also ask

How do I add afnetworking to my Xcode project?

AFNetworking supports multiple methods for installing the library in a project. To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your Podfile: Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the dependencies value of your Package.swift.

What is afnetworking/afnetworking?

GitHub - AFNetworking/AFNetworking: A delightful networking framework for iOS, macOS, watchOS, and tvOS. Loading status checks… Failed to load latest commit information. Exempt "needs investigation" from stalebot. Fix redirect test: use httpbingo service instead due to postmanlabs/h…

Does afnetworking's Swift Package include UIKit extensions?

Note: AFNetworking's Swift package does not include it's UIKit extensions. Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

How do I add afnetworking as a dependency to my package?

Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the dependencies value of your Package.swift. Note: AFNetworking's Swift package does not include it's UIKit extensions. Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.


1 Answers

Actually, I finally got it to work.

Basically, for my requestSerializer of the AFHTTPRequestOperationManager, I was using AFHTTPRequestSerializer and then trying to set the Content-Type to "application/json"

But once I switched to using AFJSONRequestSerializer instead, it works fine now

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

operationManagerInstance.requestSerializer = requestSerializer;
like image 99
user1805458 Avatar answered Oct 20 '22 00:10

user1805458