Last active
December 19, 2015 07:59
-
-
Save jonfriskics/5922163 to your computer and use it in GitHub Desktop.
Using AFNetworking to query an API endpoint in the AppDelegate before any view controllers appear
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
#import <UIKit/UIKit.h> | |
@interface AppDelegate : UIResponder <UIApplicationDelegate> | |
@property (strong, nonatomic) UIWindow *window; | |
@end |
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
#import "AppDelegate.h" | |
#import "ViewController1.h" | |
#import "ViewController2.h" | |
#import "AFHTTPClient.h" | |
#import "AFHTTPRequestOperation.h" | |
@implementation AppDelegate | |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions | |
{ | |
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; | |
ViewController1 *vc1 = [[ViewController1 alloc] init]; | |
ViewController2 *vc2 = [[ViewController2 alloc] init]; | |
NSURL *baseURL = [NSURL URLWithString:@"http://jonfriskics.com/"]; | |
// alloc init the AFHTTPClient for your baseURL | |
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; | |
// setup the request to use the GET method for a specific API endpoint (I just made this one up) and don't send any parameters | |
NSURLRequest *request = [httpClient requestWithMethod:@"GET" | |
path:@"http://jonfriskics.com/webserviceVersionApiEndpoint" | |
parameters:nil]; | |
// setup the AFHTTPRequestOperation | |
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; | |
// need to let the httpClient know that we're performing an AFHTTPRequestOperation | |
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]]; | |
// perform the operation | |
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { | |
// store the response string in an NSString variable so you can use a conditional to check the value | |
NSString *versionNumber = [NSString stringWithUTF8String:[responseObject bytes]]; | |
if([versionNumber isEqualToString:@"1.3b"]) { | |
self.window.rootViewController = vc1; | |
} else { | |
self.window.rootViewController = vc2; | |
} | |
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { | |
NSLog(@"error: %@",error.localizedDescription); | |
}]; | |
[operation start]; | |
self.window.backgroundColor = [UIColor whiteColor]; | |
[self.window makeKeyAndVisible]; | |
return YES; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment