Manjia
Manjia

Reputation: 175

Objective-c simple polling

I'm new to objective-c and I'm building an app that requires a background polling to a generic API to refresh some data on my user interface. After several hours looking for an answer/example that fits my problem I came across some solutions like the following:

long polling in objective-C

polling an external server from an app when it is launched

Poll to TCP server every hour ios

http://blog.sortedbits.com/async-downloading-of-data/

but unfortunately none of them covers my scenario which is really basic: I need to start a polling when viewDidLoad, let's say an infinite loop, and on every iteration, let's say every 10 seconds, to call an API and when I didReceiveData I want to log that data into the console with an NSLog, obviously this can't be done on the main thread.

What I really need is a very simple example on how to do that, and with simple I mean:

The solution I'm looking for could be something like this (using NSOperationQueue to run my loop into a separate thread):

- (void)viewDidLoad {
    [super viewDidLoad];
    //To run polling on a separate thread
    operationQueue = [NSOperationQueue new];
    NSInvocationOperation *operation=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doPolling) object:nil];
    [operationQueue addOperation:operation];
}

-(void)doPolling {
    MyDao *myDao = [MyDao new];
    while (true) {
       [myDao callApi];
       [NSThread sleepForTimeInterval:10];
    }
}

// and in MyDao
-(void)callApi {
    NSMutableString *url= [NSMutableString stringWithFormat:@"%@",@"http:www.example.it"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"GET";
    self.conn= [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(self.conn){
        [self.conn start];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData %s","yes");
}

but unfortunately as stated here: Asynchronous NSURLConnection with NSOperation looks like I cannot do that.

Please help, I refuse to believe that there isn't a simple straightforward solution for this basic scenario.

Upvotes: 5

Views: 2037

Answers (0)

Related Questions