Skip to content

Instantly share code, notes, and snippets.

@hbhargava7
Last active May 22, 2016 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hbhargava7/7b5656378c1dbe5046df3e8e26847e6a to your computer and use it in GitHub Desktop.
Save hbhargava7/7b5656378c1dbe5046df3e8e26847e6a to your computer and use it in GitHub Desktop.
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 (www.h2micro.com) */
- (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 *URLString = YOUR_URL_STRING;
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) {
completionBlock(deserializedJSON);
}
} 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