Yaniv Efraim
Yaniv Efraim

Reputation: 6713

Call webservice repeatingly, objective c

I have a webservice that returning 20 results each time (it is a limitation of the service provider). I want to call this service 10-20 times repeatingly and update my UI each time. Is there best practice for this situation? I do not want to block the ui while calling the server. This causes problems if the user want to perform actions while the action in progress (like navigating away from the current page) Thanks!!!

Upvotes: 2

Views: 1996

Answers (2)

Kevin Low
Kevin Low

Reputation: 2682

It depends on how you want to display the information.

If you're using the asynchronous connection (in my opinion, more effective than calling a synchronous connection in the background) and its delegate, it should not block the user interface:

- (void)loadData {
    NSString *urlString = @"http://www.stackoverflow.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

// delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // clear out or intialize instance data variable
    [myData setLength:0];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [myData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // convert data to whatever it's supposed to be (for example, array)
    NSString *dataString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

    NSArray *dataArray = [parser parseStringToArray:dataString];

    [myArray addObjectsFromArray:dataArray];

    //update tableview either using reload data (instant) or using updates (for smooth animation)
}

You can then recall the loadData method at the end of didFinishLoading: method to loop it.

Upvotes: 0

Ajeet Pratap Maurya
Ajeet Pratap Maurya

Reputation: 4254

what you can do is call the webservice in a background thread, collect the required data and jump back to main thread and update the UI.

We are doing the above(i.e jumping from background thread to main thread) because it is not recommended to update any UI in the background process.

you can call you webService in background by using

[self performSelectorInBackground:@selector(MyWebService) withObject:nil];//you can pass any object if you have

and to come back on main thread when the background task is over you can do.. [self performSelectorOnMainThread:@selector(myMainFunction) withObject:nil waitUntilDone:YES];

you can change the last parameter i.e. waitUntilDone:No also. By doing this, user will not have to wait till the UI is updated. they can carry there task.

you can use NSTimer for periodic calling your webService.

hope that helped :)

Upvotes: 4

Related Questions