When to call completionHandler in application:performFetchWithCompletionHandler: when Background Fetch is async?

人盡茶涼 提交于 2019-12-03 14:31:00

You're right — you should call the completion handler only when your fetch is actually complete. Otherwise iOS will probably put your application back to sleep before the connection completes, and apps shouldn't actually be able to determine UIBackgroundFetchResultNewData versus UIBackgroundFetchResultNoData or UIBackgroundFetchResultFailed until then anyway. How do you know your connection will succeed?

You need to keep hold of the completionHandler and call it only once the connection has finished. Most likely you'll want to add an instance variable to your delegate, copy the completion handler into there, and call it when you're done.

Aside: connection:didReceiveData: doesn't signal the end of a request. Per the documentation:

Sent as a connection loads data incrementally.

[...]

The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load.

You may receive any number of calls and the net result of the URL connection is the accumulation of all of them.

EDIT: you store a block by creating an instance variable of the correct type and copying the block to it. Blocks have unusual semantics because, unlike every other kind of Objective-C object, they're initially created on the stack. The net effect is just that you always copy them. If they're on the stack when you copy then they end up on the heap. If they're already on the heap then the copy just acts as a retain, since blocks are always immutable anyway.

So:

@implementation XXMDYourClass
{
    // syntax follow the C rule; read from the centre outwards
    void (^_completionHandler)(UIBackgroundFetchResult);
}

- (id)initWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    self = [super init];

    if(self)
    {
        // keep the block by copying it; release later if
        // you're not using ARC
        _completionHandler = [completionHandler copy];
    }

    return self;
}

- (void)somethingThatHappensMuchLater
{
     _completionHandler(UIBackgroundFetchResultWhatever);
}

@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!