How can an iOS app keep a TCP connection alive indefinitely while in the background?

yehnan picture yehnan · Apr 30, 2011 · Viewed 40.3k times · Source

An iPhone app, connecting to a remote server via TCP. The use scenarios are:

  1. app (user) sends data to server and server responds data back.
  2. server might send data to app while it does nothing.

Assume that if app does not send data to server for 30 minutes, server will close the connection. I want to keep the connection alive for 120 minutes even if user does nothing.

Case 1: if app is in foreground, I can use timer to send some do-nothing data to server. No problem.

Case 2: if user pressed Home and app went to background, what could I do? I don't wan to show alert or something to interrupt user(he is away or playing games). I just wanna keep the connection alive for a longer period and when user comes back to the app, he found out that the connection will be still alive and be happy with that.

I have read documentations about background execution, multitasking, and local notifications of iphone APIs. I'm not sure whether if I can achieve Case 2.

Only use legal APIs, no jailbreaking.

Answer

Nick picture Nick · May 1, 2011

Tapbots solved this problem with Pastebot by prompting the user to run a silent background audio track at all times.

Note that Apple frowns on using hacks like employing the background audio or VOIP APIs to keep non audio or VOIP apps running (as evidenced by the 'workaround' described in the article above) so dabbling with these techniques risks rejection at the point of submission.

Unfortunately, though, there is no legal API to keep a connection alive in the background. Perhaps they'll introduce one in a future update to iOS, but you might consider submitting a feature request to voice your support for it.