iosobjective-ccfnetwork

App running HTTP Server immediately stops listening to requests when opens Safari


I've implemented a HTTP server on my app using CFNetwork.
The server is started at some point to listen to requests via NSFileHandleConnectionAcceptedNotification.
It's working well if the requests are made when the app is active.
The problem is when I open Safari from my app to load a page provided by this server: The app goes to background and freezes. Safari seems to be waiting for the response, but the response only comes if I go back to the app.
How can I keep the server listening for these requests for some time after it switches to Safari and enters background? Or how would be a best way to implement a HTTP server to work like that? I only need it to open the page on Safari and then stop running.


Solution

  • I've found a very simple way to make it work.

    I'm creating a background task when the app is entering background.

    Just added the following code to applicationDidEnterBackground:

      __block UIBackgroundTaskIdentifier bgTask =
          [application beginBackgroundTaskWithExpirationHandler:^
      {
        dispatch_async(dispatch_get_main_queue(), ^
        {
          [application endBackgroundTask:bgTask];
          bgTask = UIBackgroundTaskInvalid;
        });
      }];