Created
June 25, 2013 16:13
-
-
Save tomhut/5859827 to your computer and use it in GitHub Desktop.
Simple example of delegate callbacks from an AFHTTPClient subclass instantiated as a singleton.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TAHAppNetClient.h | |
// Net | |
// | |
// Created by Tom Hutchinson on 15/06/2013. | |
// Copyright (c) 2013 Tom Hutchinson. All rights reserved. | |
// | |
#import "AFHTTPClient.h" | |
@protocol TAHAppNetClientDelegate; | |
@interface TAHAppNetClient : AFHTTPClient | |
@property(weak) id<TAHAppNetClientDelegate> delegate; | |
+ (TAHAppNetClient *)sharedTAHAppNetClient; | |
- (id)initWithBaseURL:(NSURL *)url; | |
@end | |
@protocol TAHAppNetClientDelegate <NSObject> | |
-(void)appNetClient:(TAHAppNetClient *)client didUpdateWithPosts:(id)posts; | |
-(void)appNetClient:(TAHAppNetClient *)client didFailWithError:(NSError *)error; | |
@end | |
// | |
// TAHAppNetClient.m | |
// Net | |
// | |
// Created by Tom Hutchinson on 15/06/2013. | |
// Copyright (c) 2013 Tom Hutchinson. All rights reserved. | |
// | |
#import "TAHAppNetClient.h" | |
@implementation TAHAppNetClient | |
+ (TAHAppNetClient *)sharedTAHAppNetClient { | |
NSString *baseURLString = @"https://alpha-api.app.net/"; | |
static dispatch_once_t pred; | |
static TAHAppNetClient *_sharedTAHAppNetClient = nil; | |
dispatch_once(&pred, ^{ _sharedTAHAppNetClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:baseURLString]]; }); | |
return _sharedTAHAppNetClient; | |
} | |
- (id)initWithBaseURL:(NSURL *)url { | |
self = [super initWithBaseURL:url]; | |
if (!self) { | |
return nil; | |
} | |
[self registerHTTPOperationClass:[AFJSONRequestOperation class]]; | |
[self setDefaultHeader:@"Accept" value:@"application/json"]; | |
return self; | |
} | |
-(void)updatePosts { | |
[self getPath:@"stream/0/posts/stream/global" | |
parameters:nil | |
success:^(AFHTTPRequestOperation *operation, id responseObject) { | |
NSArray *posts = [responseObject objectForKey:@"data"]; | |
for (id thisPost in posts) { | |
//Parse Posts | |
} | |
if([self.delegate respondsToSelector:@selector(appNetClient:didUpdateWithPosts:)]) | |
[self.delegate appNetClient:self didUpdateWithPosts:responseObject]; | |
} | |
failure:^(AFHTTPRequestOperation *operation, NSError *error) { | |
if([self.delegate respondsToSelector:@selector(appNetClient:didFailWithError:)]) | |
[self.delegate appNetClient:self didFailWithError:error]; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment