Search code examples
iosobjective-cjsonpostafnetworking-2

AFNetworkinf 2.0 json


i'm using AFnetworking 2.0 Obj-c, i'm using manager POST method with json the problem is the format of the json with v2.0 is not right it's always something like {"data" = "{"name":"name" , "age" :"30"}"} but the format i want is full json like {"data" : "{"name":"name" , "age" : "30"}"}

my code is:

`NSDictionary* dateDic = @{ @"data" : data };
AuthorizationResponse* authResponse = [[AuthorizationResponse alloc] init];
//creating connction manager
//[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)

AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];

AFJSONRequestSerializer* requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:URL parameters:dateDic success:^(AFHTTPRequestOperation* operation, id responseObject) {
    onSuccess(responseObject);
} failure:^(AFHTTPRequestOperation* operation, NSError* error) {
    //ICityError icity = [[ICityError alloc] init]
    ICityErrorItem* errorManager = [[ICityErrorItem alloc] init];
    [errorManager setCode:error.code];
    [errorManager setDescription:error.description];
    onError(errorManager);
}];

dateDic should be the dic to be parsed as json but it show me the issue i wrote

please if you answer try to give me sample of code as im new with iOS thanks in advance


Solution

  • Please find the code below to send JSON data from iOS to PHP using AFNetworking framework. Here is the github link for reference: Github link

    I have used Pod to install AFNetworking. You can do so by using the Ray's Cocoa Pods link.

    You need to setup XAMPP server on your MAC machine to access the PHP. Download XAMPP server from XAMPP download link

    Once XAMPP is downloaded and you have installed it. Run it. After that go to folder: Applications->XAMPP->xamppfiles->htdocs

    Create a new folder named - "Testing"

    Create a PHP file named "testJson.php" in XCode or any editor. Keep the extension of the file as PHP. And save that file in "Testing" folder. Once this is done. Run the project from XCode. And you will find whatever data you are sending. You will get back the data in JSON. Do not worry if it displays on console with "=" and not with ":". It is an NSDictionary and you can get the value using the valueForKey: or valueForKeyPath: or objectForKeyPath: methods.

    PHP Code:

    <?php
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    
    header('Content-Type:application/json');
    $jsonencode = json_encode($obj);
    echo $jsonencode;
    
    ?>
    

    You can send JSON data by two ways in iOS using AFNetworking

    Method1:

    - (void)method1
    {
    // Method 1
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/html",nil]];
    
    NSDictionary *dateDic = @{@"data":@{@"name":@"name", @"age":@"40"}};
    
    [manager POST:@"http://localhost/Testing/testJson.php" parameters:dateDic success:^(AFHTTPRequestOperation* operation, id responseObject) {
        NSLog(@"response %@",responseObject);
    
    } failure:^(AFHTTPRequestOperation* operation, NSError* error) {
        NSLog(@"eror %@",error);
    
    }];
    }
    

    Method 2:

    - (void)method2
    {
    // Method 2
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/html",nil]];
    NSDictionary *dateDic = @{@"data":@{@"name":@"name", @"age":@"40"}};
    
    [manager POST:@"http://localhost/Testing/testJson.php"
       parameters:dateDic
          success:^(NSURLSessionDataTask *task, id responseObject) {
              NSLog(@"response %@",responseObject);
              NSDictionary *dict = (NSDictionary *)responseObject;
    
              NSLog(@"dict %@",[dict valueForKeyPath:@"data.age"]);
    
          }
          failure:^(NSURLSessionDataTask *task, NSError *error) {
              NSLog(@"eror %@",error);
          }];
    }
    

    You can call both these methods one by one from viewDidLoad: The output will be same.