RSS Feed

Tag Archives: data

AFNetworking : How to post data (NSData) on server.

Posted on

Few of my friends are facing issue in uploading JSON data on server. I am writing this post for those developer who are new in AFNetworking and unable to upload JSON data on there web server.

1. Create your parameter dictionary as : 
 NSDictionary *jsonDic = [NSDictionary dictionaryWithObjectsAndKeys

 value,         @”key”,

 value,         @”key”,

 value,         @”key”, // etc

                         nil];

2. Convert this dictionary into data : 

NSError *error = nil;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&error];

3. Now follow this to upload data on server :

// Create request body 

    NSMutableData *body = [NSMutableData data];

// Append of the body with your data

    [body appendData:jsonData];

        [request setHTTPBody:body];

// Set request method POST

     [request setHTTPMethod:@”POST”];

// Set request Headers

    [request setValue:@”application/json” forHTTPHeaderField:@”Accept”];

    [request setValue:@”application/json” forHTTPHeaderField:@”content-type”];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

 // Success

  NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

              NSDictionary *responseDict = [responseString JSONValue];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

// Failure

        NSLog(@”Error: %@”, error);

    }];

      [operation start];

 

Cheers !!