Search code examples
objective-cafnetworkingafnetworking-2

AFNetworking is not sending a request


I am trying to learn AFNetworking by trying to create a simple commandline app. The network request is not being made at all. I used charles proxy to see if any requests are being made to the api server but none are being made. Any pointers?

#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {   
    NSString * BaseURLString = @"http://api.erail.in/pnr?key=599c6647e&pnr=673607";
    NSURL *url = [NSURL URLWithString:BaseURLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    NSLog(@"Hi!");
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *status = (NSDictionary *) responseObject;
        NSLog(@"HI!");
        NSLog(@"%@", status);

    }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Couldn't reciev the data");
                                     }
     ];
    [operation start];
    }
return 0;
}

Solution

  • The request runs asynchronously, and as a result the main function is ending, and thus the app is terminating, before the request is done.

    You need to have an NSRunLoop running to keep the app alive and process AFNetworking's NSURLConnection events properly. The easiest way to do that is to not use a command line app, but instead use a standard Cocoa or Cocoa Touch app, and start the AFHTTPRequestOperation in the appropriate place. The NSRunLoop will keep running, the app won't immediately terminate, and AFNetworking's NSURLConnection will have a chance to process the request and await the response.

    If you really want to do a command line app, then you can keep the run loop alive yourself:

    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            BOOL __block done = NO;
            NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    
            AFHTTPRequestOperation *operation = ...
            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                // do your success stuff
    
                done = YES;
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                // do your failure stuff
    
                done = YES;
            }];
            [operation start];
    
            while (!done && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
                // this is intentionally blank
            }
        }
        return 0;
    }