Taz
Taz

Reputation: 65

how to call webservice periodically in background iphone?

I have web service and i want to call this service periodically from my iPhone application to cash the data every 1 min when the application is running .

I use NSTimer to call the function that call this service but i what to be sour that the first call did finish parsing the data from the first call before proceed a new call . so how can i do that ?

{
 NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
 NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                                      interval: 10
                                        target: self
                                      selector:@selector(calltimer:)
                                      userInfo:nil repeats:YES];

 NSRunLoop *runner = [NSRunLoop currentRunLoop];
 [runner addTimer:t forMode: NSDefaultRunLoopMode];
 [t release];
}

-(void)calltimer :(id)sender
{
    NSLog(@"yessss");

    if(!myQueue)
    {
        myQueue = dispatch_queue_create("supperApp.user1025523.com", NULL);
        dispatch_async(myQueue, ^{
            [self getData]; 
            });
    }    
}

-(void)getData
{
    webserviceCaller* wsCaller = [[webserviceCaller alloc]initWithTarget:self     selector:@selector(parsINVData:)];
    [wsCaller getINventoryData:self.username];
    [wsCaller release];
}

-(void) parsINVData:(InvData*) ret
{
    //save return data in global variable      
}

I use NSMutableURLRequest to initiate the request parameter and NSURLConnection to start the connection so why the call to the web service didn't fire .

Upvotes: 0

Views: 1743

Answers (2)

jscs
jscs

Reputation: 64002

Use a serial queue to ensure that one task waits for the next.

- (id)init
{
    self = [super init];
    if( !self ) return nil;

    parsing_queue = dispatch_queue_create("superApp.user1025523.com", NULL);

    // etc.

- (void)timerAction: (NSTimer *)tim
{
    // Enqueue the work. Each new block won't run until the 
    // previous one has completed.
    dispatch_async(parsing_queue, ^{
        // Do the work
    });
}

This also automatically in the background.

Upvotes: 1

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

You can add a class level member variable like the following:

in .h file

{
    BOOL finishedParsing;
}

- (void) nsTimerFunctionCall
{
    if(!finishedParsing)
    {
        //Either return, or recall this same function after some time
        return;
    }

   [self parseCode];
}

- (void) parseCode
{
    finishedParsing = NO;

    //do long processing function
    //....

    finishedParsing = YES;
}

This way you can ensure that the parse code will not be called while another call to the function is processed

Upvotes: 2

Related Questions