gcdasyncsocket background file transfer

2019-09-10 10:24发布

问题:

Having two devices that need to keep transferring data while in background or in LockScreen.

The main resource about backgrounding is available on https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

So far I'm looking forward to understand how is it expected to implement such above mentioned behaviour: in a scenario where a transfer is in progress and one of the apps (or both) goes into background. Obviously we have resumable transfer management working already.

I've been collecting stubs and answers about and I've ended up with the following:

  1. Ensure every socket is backgroundable.

    [socket performBlock:^{
             [socket enableBackgroundingOnSocket];
         }];
    
  2. To keep backgrounding even when in Lock Screen, I read an answer saying that we should have something like at the end of didFinishLaunchingWithOptions but what code is in [self backgroundHandler] method?

    BOOL backgroundAccepted = [[UIApplication sharedApplication]
    setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
    if (backgroundAccepted)
        NSLog(@"background handler accepted");
    
    return YES;
    
  3. The applicationDidEnterBackground delegate method of UIApplication shows

    - (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"=== DID ENTER BACKGROUND ===");
        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
        NSLog(@"Multitasking Supported");
    else
        return;
    
    // Shall I remove my KVO observers when in background?? I guess NOT, right? :D
    //[[NSNotificationCenter defaultCenter] removeObserver:self];
    
    UIBackgroundTaskIdentifier bgTask = [[UIApplication  sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    NSLog(@"End of tolerate time. Application should be suspended now if we do not ask more 'tolerance'");
    // [self askToRunMoreBackgroundTask]; This code seems to be unnecessary. I'll verify it.
    }];
    
    if (bgTask == UIBackgroundTaskInvalid)
        NSLog(@"This application does not support background mode");
    else
        NSLog(@"Application will continue to run in background");
    
    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    });
    

回答1:

I got it working following this tutorial but looks like GCDAsyncSocket is no longer maintained so it will work only on iOS7.

http://www.objc.io/issue-5/multitasking.html

To do background file transfer under iOS 8 I am using AFNetworking library (http://afnetworking.com)