Search code examples
iosiphonewifibackground-process

How to implement UIRequiresPersistentWifi to work application in the background


My application needs persistent wifi connection in the background, I think the only way to do is to apply UIRequiresPersistentWifi to info.plist file. So, below is what I have added to info.plist,

I added UIRequiresPersistentWifi with YES.

I added Required device capabilities with wifi

I created NSInputStream, NSOutputStream streams in code. Even after doing all these sockets does not work in the background. What else am I missing?

Should I add any code to - (void)applicationDidEnterBackground:(UIApplication *)application delegate method ?


Solution

  • Yes, we have to add code in applicationDidEnterBackground as below.

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
            // Clean up any unfinished task business by marking where you
            // stopped or ending the task outright.
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];
    
        // Start the long-running task and return immediately.
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        
            // Do the work associated with the task, preferably in chunks.
            bgTask = UIBackgroundTaskInvalid;
        });
    }