Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@goliatone
Created September 18, 2013 23:05
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 goliatone/6616995 to your computer and use it in GitHub Desktop.
Save goliatone/6616995 to your computer and use it in GitHub Desktop.
//
// GServiceGateway.h
//
//
#import <Foundation/Foundation.h>
@interface GServiceGateway : NSObject
- (BOOL)connectionPOST:(NSString *)url
withParams:(NSDictionary *)aDictionary;
- (BOOL)connectionPOST:(NSString *)url
withString:(NSString *)aString;
@end
//
// GServiceGateway.m
//
#import "GServiceGateway.h"
@implementation GServiceGateway
- (BOOL)connectionPOST:(NSString *)url
withParams:(NSDictionary *)aDictionary {
if ([aDictionary count] > 0) {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:url]
];
[request setHTTPMethod:@"POST"];
NSMutableString *postString = [[NSMutableString alloc] init];
NSArray *allKeys = [aDictionary allKeys];
for (int i = 0; i < [allKeys count]; i++) {
NSString *key = [allKeys objectAtIndex:i];
NSString *value = [aDictionary objectForKey:key];
[postString appendFormat:( (i == 0) ? @"%@=%@" : @"&%@=%@" ), key, value];
}
NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
postString = nil;
request = nil;
return YES;
} else {
return NO;
}
}
- (BOOL)connectionPOST:(NSString *)url
withString:(NSString *)aString {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:url]
];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString *postLength = [NSString stringWithFormat:@"%d", [aString length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:[aString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
request = nil;
return YES;
}
@end
@goliatone
Copy link
Author

GServiceGateway* gateway = [[GServiceGateway alloc] init];

NSString* url = @"http://example.com/end-point";
NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys:json,@"data", nil];

[gateway connectionPOST:url withParams:data];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment