Search code examples
phpobjective-cjsonpostafnetworking-2

iOS - AFNetworking failure while connecting PHP page


I created an online PHP page in Cloud9 in which i can connect to a MySQL db and do whatever I want to do. I can connect that page from my iOS application simulator without using AFNetworking. However, i should use this library and create a POST request. My POST request fails and gives this error:

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.) {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

My Objective-C code is:

NSString *url = [URLFactory targetURL];
NSDictionary *dictionary = @{
                             @"key" : @"value",
                             };

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:url parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
     NSLog(@"Response : %@",responseObject);
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

     NSLog(@"Here!");

     NSLog(@"Error : %@",error);
 }];

And PHP:

<?php 
header('Content-type: application/json');
$isPostRequest = $_SERVER['REQUEST_METHOD'] == 'POST';

if ($isPostRequest) {

    echo json_encode("done!");
}
?>

As you can see, i'm not doing anything yet. I'll check paramters but for now i just want connection. I see "Here!" log and get error. Am i doing something wrong or is there something missing? I found some posts about this error but they are not in failure situation. Thus i'm confused.

Thank you!


Solution

  • Try changing your code to make an array like so:

    echo json_encode(array("response" => "done!"));
    

    Then in your iOS code, get the response object:

    NSArray *jsonObjects = [responseObject objectForKey:@"response"];