iPhone app, running http requests while applicatio

2019-01-25 00:46发布

问题:

In my iPhone app I would like to run several queries when the application is in background. I already use ASIHttpRequest to make the queries, that works fine but now I try to find a way to trigger them in background. In the app delegate, I have added a call to the method making the request:

   [self getItemsFromServer]

getItemsFromServer runs an asynchronous request (on the simulator I saw the log of this methods once I get back the application to the foreground). How can I use some kind of timer to have this method ran every 10 minutes (I just need to run it 4 or 5 times, not each 10 minutes until it goes back to foreground :-) )?

thanks a lot,

Best Regards,

Luc

回答1:

iOS4 allows your app to run for X amount of time, granted that iOS4 grants you the time you request. Check out: Completing a Long-Running Task in the Background.

Specifically,

Any time before it is suspended, an application can call the beginBackgroundTaskWithExpirationHandler: method to ask the system for extra time to complete some long-running task in the background. If the request is granted, and if the application goes into the background while the task is in progress, the system lets the application run for an additional amount of time instead of suspending it



回答2:

You could probably use Task Finishing to do that. In iOS you can mark a thread as finishing and give it a specific time to live. This would let you do a few more calls to your web server.

Have a look at Executing Code in the Background



回答3:

Actually, you are specially not allowed to make general HTTP calls while in background. The only apps that can be active in the background are those that play audio, do location or are running VOIP calls. I believe Apple's whole philosophy with background is that apps shouldn't be doing 'work' other than these limited cases because there are limited resources available. THe suggested way to work around this is to use (ugh) notifications or just do a refresh when your application wakes up. The doc that willcodejavaforfood references explains this.