Running the code when application is in the background or device is locked - iphone

I have a piece of code wherein I make a server call and based on the response I play a sound. Now, this does not work when my application is in background or my devicei is locked.
Is there any way we can execute this piece of code (Server call and response handling) even if app is in background or device is locked?

There is no general solution, which is by design. (Apple does not want you to have a potentially CPU- and power-intensive process running in the background and degrading user experience.)
There are a few limited-case options available:
You said you want to play a sound. If by this you mean "play music" or some such streaming, there is an audio background task that your application can register to perform. Note that you must actually be streaming audio; Apple rightfully frowns upon apps that try to use this approach to circumvent the general-case prohibition and will reject your App Store submission accordingly.
You can invert your scenario and have the server send a push notification through the Apple Push Notification service. Depending on the user's settings, an alert, badge, or sound can result. This might be the best fit for you if you aren't streaming audio.
If what you are really intending to do is, say, finish an upload or download (and the sound is a completion notification), you can request some additional time to finish that task after the app is nominally backgrounded or the device locked. Use -[UIApplication beginBackgroundTaskWithExpirationHandler:] from within the appropriate UIApplicationDelegate methods to register such a task. Note that you have a limited (but appreciable) amount of time to finish your task, and I don't think you can play media in this mode.

Related

iphone: backgrounded app sync webservice

I know this question may be a little bit common and over asked but I cannot find any precise information... so :
Is it possible to have some kind of thread running when the app is in background so I can perform basic sync with my webservice ?
App is in background : I mean the user clicked the Home button, or switched to another app
basic sync : photo upload and download with AFNetworking. I know it has method to continue an HTTPRequest while app is in background, but this is not my point.
My goal would be to make some kind of sync manager, reading a list of photos to update created while the user was on the app, and perform those changes.
I know that the manager could be killed by the OS, but since my server uses atomic transfers it is not a problem. I just need a way to relaunch it... Push ?
I think apps like Google Latitude or Mail and those kind of apps uses what I am looking for but I cannot find any relevant details on it. And using iOS5 is not a problem but waiting for iOS6 would not be a solution.
Thank you for your replies !
PS : well I almost forgot. the app is designed for an enterprise program, so maybe rules are different ? I don't think there is any check for in-house deployment so it might lead to new possibilities...
Apple's Mail client has a background daemon which keeps it running but you can't have that with your own applications. Once an app enters a background state, it must halt it's operations. You can request for a little more time when backgrounded to finish off any transfers or writes to disk (see the Executing a Finite-Length Task in the Background section on Apple's Multitasking Guide)
Google Latitude has events generated based on location. This is a special type of backgrounding introduced by Apple for certain types of applications (see Implementing Long-Running Background Tasks section on Apple's Multitasking Guide) but this can't be used for HTTP syncing. It can only be used for audio, location, voip, newstand content, bluetooth and external hardware attachments.
Push doesn't seem like a solution because it only generates an alert. It doesn't trigger any action until the user triggers the opening of the notification.
You'll want to read Tech Note 2277 Networking and Multitasking.
Basically you have a couple of options:
If you can convince Apple that your app is a VoIP app then you can register a VoIP socket and the OS will resume your background app whenever there is activity on that socket.
Your main option though is to register a background task for any outstanding activity that you have to do when your app is put in the background. You typically get 10 minutes to finish up that work.
Mail is a special app with privileges you don't get.
Apps like Latitude typically register themselves for location updates, specifically to be woken up when there are major geo-position changes. Apps that record GPS tracks do similar things.
Found it !
Using Suhail Patel 's link on Apple's Multitasking Guide I added the voip tag to UIBackgroundModes in Info.plist and use setKeepAliveTimeout:handler: method of UIApplication to relaunch it if needed once the app is going to sleep.
I hope this will help a lot of you !
Of course this app won't be allowed to be on the App Store but for in house development this is in my opinion the best way to do so.
Thanks everyone for showing me the right direction !

app runs in background on ios4

I hope to run an app in background on ios4
I know
Apple allows only certain types of apps to run in the background, like navigation and audio and VOIP apps. But even those are limited to only the necessary tasks.
Is it possible I register the app as one kind of VoIP, Audio or GPS apps to keep it run in background?
Welcome any comment
You can't "run" an app in the background; you can only run a task in the background. The tasks are
Continue Playing Audio
Maintain VoIP Connection
Update Location (GPS)
Some Finite Task (such as uploading a file)
I haven't developed for iOS so there might be something I'm missing. Read more at Executing Code in the Background. As of iOS 4, developers don't have the ability to implement true multitasking. Correct me if I'm wrong in any of this.
Not in general, no. You could register a VoIP or GPS session and abuse its callbacks for certain tasks, but I doubt the App Store review process would take kindly to it.
What do you need to do in the background that isn't covered by task completion or the audio/VoIP/GPS background modes? it might be possible to use another paradigm and still get the cake.

Can an app reliably upload data when it is backgrounded?

The docs don't seem to offer any guarantees - I'm just wondering if anyone's had any experience of uploading a large amount data after a user 'backgrounds' an iPhone app.
E.g., recording some audio or video and uploading it while there's the possibility that the user will start another app. Is is reasonable to expect to be able to be able to upload several MB of data in the background, perhaps using the VOPI UIBackgroundMode, which should keep sockets active?
First, uploading anything that is not VoIP data in a VoIP background mode violates Apple's guidelines and will probably get your app rejected. But you still have the option of using the normal background task completion API that gives your app another 10 minutes (at the moment, the amount might change in a future release) to finish a task like an upload.
If a foreground app uses a large amount of bandwidth, it is likely that the OS will give it priority over the background task.
Of course, you cannot rely on your upload being finished. If you run out of time, the system will notify you and you should try to resume the upload when the user reactivates your app. But you can't rely on a stable internet connection anyway, even if your app is in the foreground, so I don't really see the difference.
NO, this is not possible. i agree that it creates problems when you have a long operation to make but it is defiantly not possible.

iPhone sdk, Running app in background and send frequent http request

I am trying to take advantage of iPhone 4 multitasking feature. I want to run app in background and frequently send http request to send/receive data, is it possible?
Surprisingly, there is actually very little time-slicing going on in the "multi-tasking" iOS 4.x. What goes on instead is really just application suspend / resume. When an application is sent to the background upon the user tapping the home button, it will stop getting execute cycles after a short while (*).
(*) There are a few exceptions. Applications which declare themselves as "VoIP providers", location-based apps, and music apps can get background execute cycles, presumably only though to perform those very specific operations in response to corresponding events (like a "significant change in location" occurring). Some apps apparently try to stretch the rules and find undocumented or not-strongly-documented techniques to continue getting background execute cycles.
And the "requested running time" that Undeadlegion mentioned is limited in duration.
The reality is that on iOS4, applications are not allowed to run continuously in the background.
#Undeadlegion has suggested a plausible way to achieve your goal. To be more clear, take a look at my previous answer to a similar question at SO, iphone - Connecting to server in background
It is possible to request running time while your app is backgrounded.
See Multitasking Developer's Guide
Although, depending on the intent of your http requests, push notifications may be a viable alternative.
This may be necessary because you aren't providing audio, voip, or location services, so your app can't run in the background indefinitely.

Can an iPhone App take exclusive control or reliably record why it lost control

I am trying to determine feasibility of certain features required in a (potential) project. I am not (yet) looking for a how-to, just a can-do. I apologize for any vagueness and ignorance: the former due to an NDA that makes Apple's NDA look like GPL, and the latter due to the fact that I have no iPhone or MAC experience.
I do have a solid understanding of objective-c and interface builder (going back to NextStep) and some PDA development experience, so I'll probably understand the answers, even if my questions are naive. I have done a bit of browsing, so I know some buzzwords.
I can't go into detail about the actual project, but I have come up with a lame analogy.
a large number of users in the same room are asked to complete task(s) in the app (say a puzzle)
they are under supervision, but the monitor cannot watch them all closely
they are not allowed to leave the application until done.
they cannot send/receive phone calls or messages during the task.
the monitor receives notification of various steps during the task
the monitor is notified when the task is completed, or the app is exited
the app sends a heartbeat, so the monitor also knows if signal is lost
Jailbreak is not an option.
The app should also work on iPod Touch.
So the things I need to do that seem dicey to me are
can I turn off (or require the user to turn off) phone and sms but still be able send http to my server
can I prevent an app from being switched out (even if, say an alarm app triggers or the phone rings).
failing prevention, can I at least detect any of these events and notify my server.
failing notification, can I record the event for the monitor to check later.
The user will be aware (and in fact welcome) these restrictions. It's a trust issue - the user must not seek help or use a helper app to solve the puzzle, and wants the monitor (and other contestants) to know that he did not. It's feasible for the user to click on an "OK, I understand and approve" screen at the beginning, but not for each communication to the server.
The app would only communicate with a central server (run by my company) - the monitor would not be able to buy the server software, and the url's of the server would not be user (or monitor) modifiable.
Hey! This looks like an app for taking exams. Not what I am doing, but that would be cool too!
EDIT --
I changed the title and am adding a few more parts to the question, based in part on mmc's answer. The App may run in an offline mode that would have to do the following:
So using the exam analogy, the user off line experience would be something like this
Launch App
App download test questions, registers start time, etc.
Turn off phone (if app can't do it by itself)
Disable any app that might interrupt my App (can app do this?)
Resume and Take Test
Indicate test done (or finish last problem).
Turn on phone (if app can't) and restart App (if needed).
App uploads test results and log of any interruptions.
So the question becomes
Am I sure that I at least get to log any interruption I can't prevent
can I know the cause of the interruption (phone answered, alarm launch, user initiated)?
can the user be prevented from modifying the log
can I know what other Apps are running when I start? (to guard against a daemon that occasionally displays a hint or something.
I would still like to run with real time uploads, so a few other ideas come to mind.
If I can reliably detect and record that the phone or another app was used, that might be almost as good as preventing it.
Can the user prevent the phone from ringing even if it's on (eg. call forward + ringer off)
Can my app know if the ringer is off
Same question for sms messaging
If I can't block it, can the user just ignore (silent) call or message and not leave my App. Would my app know that?
Sounds like you might be better off doing away with the phone, and making it exclusive to the iPod Touch.
You've nailed your trouble spots.
There is no way to disable phone functionality, and at the same time maintain network functionality of any type (3G, WiFi, or bluetooth) If you disable the phone operations with Airplane mode, all of them are disabled.
There is no way to prevent the Home button from returning you to Springboard
You can notify a server of a premature app interruption (there is an applicationWillTerminate: method on your app delegate) but is not reliable. If the operation takes too long, your app will be forcibly terminated.
You could write to the local file system that a premature interruption happened, and this would be far more reliable, as this operation would be much faster.