iOS - background fetch and threads -
i have app, uses background fetch , update location during it. works fine code:
-(void)backgrounddidupdatelocations:(nsarray *)locations { uiapplication *app = [uiapplication sharedapplication]; __block uibackgroundtaskidentifier locationupdatetaskid = [app beginbackgroundtaskwithexpirationhandler: ^{ dispatch_async(dispatch_get_main_queue(), ^{ if (locationupdatetaskid != uibackgroundtaskinvalid) { if (_backgroundfetchcompletionhandler != nil) { nslog(@"bg location finished 1"); _backgroundfetchcompletionhandler(uibackgroundfetchresultnewdata); _backgroundfetchcompletionhandler = nil; } [app endbackgroundtask:locationupdatetaskid]; locationupdatetaskid = uibackgroundtaskinvalid; } }); }]; dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{ if (_delegate && [_delegate respondstoselector:@selector(mylocationmanager:didupdatelocations:)]) { [_delegate mylocationmanager:self didupdatelocations:locations]; } dispatch_async(dispatch_get_main_queue(), ^{ if (locationupdatetaskid != uibackgroundtaskinvalid) { if (_backgroundfetchcompletionhandler != nil) { nslog(@"bg location finished 2"); _backgroundfetchcompletionhandler(uibackgroundfetchresultnewdata); _backgroundfetchcompletionhandler = nil; } [app endbackgroundtask:locationupdatetaskid]; locationupdatetaskid = uibackgroundtaskinvalid; } }); }); }
but there problem this:
[_delegate mylocationmanager:self didupdatelocations:locations];
if use simple call, fine. if _delegate
method runs background operation, download data internet, have problem. download started asynchronously, background fetch "closed" backgroundfetchcompletionhandler
before data delivered. data delivered outside of scope , afraid, can cause problems. how solve problem correctly?
edit: can not modify _delegate
code, pass handler variable not option.
if delegate set , responds pass completion handler can work , call completion handler when it's done. if delegate isn't set or doesn't respond call completion handler directly.
Comments
Post a Comment