ios - One task with multiple threading and different viewcontrollers -
i'm still facing problems multithreading on ios. want fetch json in mainviewcontroller (when app launches) , populate left menu (swrevealviewcontroller) data.
but let's consider situation low internet speed, when user reveals menu , data didn't come mainviewcontroller. i'm fetching json both controllers. don't know how make sidebar wait data until mainviewcontroller finishes fetching?
call mainviewcontroller
[[categoriesstore sharedstore] fetchdatawithcallback:^(nsarray *allcategories, nserror* error) { }];
call sidebarviewcontroller inside async blocks
[[categoriesstore sharedstore] fetchdatawithcallback:^(nsarray *allcategories, nserror* error) { if (error) { } else { //[self.tableview beginupdates]; blocksafe.alldirectories = allcategories; [blocksafe.tableview reloadsections:[nsindexset indexsetwithindex:1] withrowanimation:uitableviewrowanimationfade]; } }];
fetching json categoriesstore (singleton model)
+(instancetype)sharedstore { static categoriesstore *sharedstore = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedstore = [[self alloc] initprivate]; }); return sharedstore; } - (instancetype)initprivate { self = [super init]; if (self) { [self sessionconf]; _allcategories = nil; } return self; } - (void)fetchdatawithcallback:(void(^)(nsarray *allcategories, nserror* error))callback { nslog(@"categoriesstore - %@",self.description); @synchronized(self) { if (!_allcategories) { nsurlsessiondatatask *getcategories = [self.session datataskwithurl:categoriesurl completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { if (error) { nslog(@"error - %@",error.localizeddescription); callback(nil, error); return; } nserror *jsonerror = nil; nsarray *json = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:&jsonerror]; if (!jsonerror) { _allcategories = json; nslog(@"categories fetched"); callback(_allcategories, nil); } else { callback(nil, jsonerror); } }]; [getcategories resume]; } else { callback(_allcategories,nil); } } }
thanks , advices!
you can this: dispatch_group_t group_t = dispatch_group_create();
dispatch_group_async(group_t, dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ //do first thing }); dispatch_group_async(group_t, dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ //do second thing }); dispatch_group_notify(group_t, dispatch_get_main_queue(), ^{ //update ui });
Comments
Post a Comment