Saturday, May 21, 2011

iOS: Fixing the WiFi connection closed after 30 minutes

One nice Saturday afternoon when I was doing almost nothing, I got a phone call.  The number was big and didn't look like it was from India.  I picked up the call and said "Hello...", a familiar voice replied back.  The voice was of one of my good friend.  This friend of mine had gone to Germany for a month, his iOS project was going live.  He had called me that afternoon to discuss about a problem that he was facing in his app.  

The Problem

The application was to be deployed on iPad.  Application used to poll the server for updates every 10 seconds.  For the application to work correctly, it was necessary that the polling should work flawlessly.

This polling worked well, however, he was facing one ugly little problem.  The issue was, after about 30 minutes, the polling would stop and because of this the application would not function correctly after 30 minutes.  This would happen only if the iPad is not connected to the charger or a computer.  If the iPad was connected to the charger or a computer polling would function correctly for any duration.

The workaround

To get the polling to work again user has to do one of the following
  • Connect the iPad to a power source i.e. a charger or a computer
  • Pressing the home button on the iPad and reopen the application
The Fix

I had not faced this issue earlier.  In fact, I have not done much iPhone development (at least non yet), but I decided to give it a shot anyways.  I decided to google about this issue and find a fix.

After some intense googling, I found that, iPad switches off the WiFi connection automatically after 30 minutes to preserve battery.

That's a good strategy alright but, what about the apps like my friends app?  The app need to poll the server every 10 seconds to function correctly.  How can we stop the iPad from switching off the WiFi connection automatically after 30 minutes?

The fix was pretty simple, One needs to set a property in the property list file.  The property is called UIRequiresPersistentWiFi.

Quoting from the Apple developer documentation
UIRequiresPersistentWiFi (Boolean - iOS) specifies whether the application requires a Wi-Fi connection. iOS maintains the active Wi-Fi connection open while the application is running.
 That was it!  I knew that, I have found a fix to my friends problem.  Asked him to add the property to the plist file and do a test again.  As expected the problem was solved.  Now, the app was able to poll the server for any duration without a problem even when the iPad was not connected to the power source!

Simple things like this waste a lot of developer time, but once you learn something the hard way, you will never forget it!
Have some Fun!