Search code examples
iphoneios6

How to fetch data from web service in background and then update the UI


What i am doing is applying push view controller to move to next view from table view's didSelectMethod. And on next view controller data is fetched for that view. So, the problem is the view switches only when the data is fetched completely, and it contains images and text both. But i have already applied the lazy loading for images but the issue is to move to next view immediately and then fetch data and update the UI and tableview. Below is code i am trying.

On next view controller's didLoad method.

 [NSThread detachNewThreadSelector:@selector(setImage) toTarget:self withObject:nil];

the method setImage fetching all data images and text.

-(void)setImage
{    
        if([type isEqualToString:@"Organisation"])
        {
            self.mGetDataDict = [MyEventApi members:self.mUserIdDict];
            self.mRecievedDataDict = [self.mGetDataDict valueForKey:@"members"];
        }
        if([type isEqualToString:@"Individual"]){
            self.mGetDataDict = [MyEventApi friends:self.mUserIdDict];
            self.mRecievedDataDict = [self.mGetDataDict valueForKey:@"friends"];
        }

        if([self.mGetDataDict valueForKey:@"friends"] == [NSNull null])
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"alert" message:@"You have not added any friend yet." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
        else
        {
            self.mFrndNameArr = [[NSMutableArray alloc]init];
            self.mFrndImgArr = [[NSMutableArray alloc]init];
            self.mFirstNameArr = [[NSMutableArray alloc]init];
            self.mLastNameArr = [[NSMutableArray alloc]init];
            self.mFrndIdArr = [[NSMutableArray alloc]init];
            self.mFrndMSinceArr = [[NSMutableArray alloc]init];
            self.mFrndDescArr = [[NSMutableArray alloc]init];

            self.mFrndNameArr = [self.mRecievedDataDict valueForKey:@"username"];
            self.mFrndImgArr = [self.mRecievedDataDict valueForKey:@"image"];
            self.mFirstNameArr = [self.mRecievedDataDict valueForKey:@"firstName"];
            self.mLastNameArr = [self.mRecievedDataDict valueForKey:@"lastName"];
            self.mFrndIdArr = [self.mRecievedDataDict valueForKey:@"id"];
            self.mFrndMSinceArr = [self.mRecievedDataDict valueForKey:@"memberSince"];
            self.mFrndDescArr = [self.mRecievedDataDict valueForKey:@"description"];

             [self.mFriendsTable reloadData];
        }    
 }

Please guide for above, is i am using correct method or there is another way to do this. Thanks in advance.


Solution

  • you can use GCD

       dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
            //Fire api
            dispatch_async(dispatch_get_main_queue(), ^{
              //update ui
            });
        });