How I do basic networking
I know the awesome [AFNetworking framework](http://afnetworking.com) by [Mattt Thompson](http://mattt.me) even though I haven't used it yet. The reason for not using it is, that in all the projects I did so far I only needed basic requests to easy to use APIs. Using AFNetworking would have been an overkill. In additions I am still learning and needed first to develop my own style of using the networking frameworks that Apple provides.
Here is how I do network requests these days.
To have all the definitions of the API endpoints in one spot, I define static functions at the top of my networking class. (I'm using the App.net-API as an example.)
[code language="objc"]
static NSString *baseURLString = @"https://alpha-api.app.net/stream/0/";
static NSURL *globalStreamURL(void) { return [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", baseURLString, @"posts/stream/global"]]; }
[/code]
As I create several `NSURLRequests` I have helper methods to construct those.
[code language="objc"]
- (NSURLRequest*)requestWithURL:(NSURL*)url method:(NSString*)restMethod body:(NSDictionary*)body
{
NSArray *allowedMethodNames = @[@"GET", @"POST", @"DELETE"];
NSAssert([allowedMethodNames containsObject:restMethod], @"Only GET, POST and DELETE are allowed as rest methods at the moment.");
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
urlRequest.HTTPMethod = restMethod;
if (body) {
NSError *jsonError = nil;
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:body options:kNilOptions error:&jsonError];
if (jsonError) {
return nil;
}
urlRequest.HTTPBody = bodyData;
}
return urlRequest;
}
- (NSURLRequest*)postRequestWithURL:(NSURL*)url body:(NSDictionary*)body {
return [self requestWithURL:url method:@"POST" body:body];
}
- (NSURLRequest*)getRequestWithURL:(NSURL*)url {
return [self requestWithURL:url method:@"GET" body:nil];
}
[/code]
The actual API call is a public method with a completion block.
[code language="objc"]
- (void)fetchGlobalStreamWithCompletion:(void(^)(NSArray *globalPostsArray, NSError *error))completion {
NSURLRequest *urlRequest = [self getRequestWithURL:globalStreamURL()];
NSURLSession *session = [self sessionWithDefaultConfig];
NSURLSessionTask *sessionTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError *jsonError = nil;
NSDictionary *responseDictionary = nil;
if (!error) {
responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
NSLog(@"responseString: %@", [data stringValue]);
globalPostsArray = responseDictionary[kDataKey];
error = jsonError;
}
if (completion) completion(globalPostsArray, error);
}];
[sessionTask resume];
}
[/code]
As I'm only using `NSURLSessions` with default config I have a helper method to construct those.
[code language="objc"]
#pragma mark - Session with default config
- (NSURLSession*)sessionWithDefaultConfig {
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
return [NSURLSession sessionWithConfiguration:sessionConfiguration];
}
[/code]
In the next post I will share how I test this code.