Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Asynchronously send an NSDictionary to a server PHP (or other) script using JSON with a completion handler (Objective C).
/* Created by Hersh Bhargava of H2 Micro ( */
- (void)sendDictionary:(NSDictionary *)dictionary toScript:(NSString *)scriptName completion:(void (^) (id response))completionBlock
//Convert the passed dictionary into JSON.
NSString *JSONStringfromDictionary = [self JSONfromDictionary:dictionary];
//Set up the query string for the Server with the API Key inline.
NSString *queryString = [NSString stringWithFormat:@"%@key=%@", URLString, YOUR_OPTIONAL_API_KEY];
//Create a URLRequest using the query string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[queryString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
request.HTTPMethod = @"POST";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//Convert JSON string to NSData object
NSData *dataFromJSON = [JSONStringfromDictionary dataUsingEncoding:NSUTF8StringEncoding];
NSString *stringifiedData = [[NSString alloc]initWithData:dataFromJSON encoding:NSUTF8StringEncoding];
request.HTTPBody = dataFromJSON;
//Execute Asynchronous request with a completion handler block.
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSError *deserializationError;
id deserializedJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&deserializationError];
if (deserializationError) {
NSLog(@"NetworkManager: Failed Deserialization: %@", deserializationError.description);
NSLog(@"NetworkManager: Failing string from script. \"%@\": %@", scriptName, receivedString);
} else {
NSLog(@"NetworkManager: Succesfully deserialized JSON from script \"%@\": %@", scriptName, [self dictionaryWithoutBigKeysFromDictionary:deserializedJSON]);
//Call completion handler with deserialied server response as a parameter.
if (completionBlock) {
} else {
NSLog(@"NetworkManager: failed to connect to server: %@", connectionError.description);
-(NSString *)JSONfromDictionary:(NSDictionary *)dictionary
NSData *jsonData;
@try {
jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
@catch (NSException *exception) {
NSLog(@"Failed JSON Serialization: %@", exception);
return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.