How to run run a process frequently as a background service ios - ios

I am working on ios app that used to read ticket data as a barcode scanner. It needs to upload data frequently to a web server, Like two or three times a day. I have done the sync function. I just wanted to run the function when the app is run in background.

This is not possible on iOS, Apple is not allowing any kind of background service on iOS.
The options you are left with is setting your apps background mode to fetch and implement application:performFetchWithCompletionHandler:. But it is totally up to ios if and when this method is called.
You could misuse one of the other background modes to keep your app open in the background, but Apple might reject your app for doing so. Also user might complain about you app draining battery.
What kind of data is that you need that you have to update it two to three times a day? I would say the when the app is opened by the user would be a good time to update, because this is when the user is expecting new data.
If you need to inform the user about some data changes you should be pull it in the app but a server should send a push notification to inform the user that there is new data.

Related

iOS Backrground Sync Alternative for enterprise apps?

I have been investigating iOS background fetch for our enterprise applications. According to articles like this, there are limitations like having 30 seconds to download before the app is terminated and the may be (unconfirmed) a penalty where after 3 timeouts, an app gets banned from background sync. Also if the user kills the app, fetches stop happening -noted here.
The goal is to be able to retrieve data from our servers periodically when app is suspended/not running but sometimes the transfers can take minutes due to long running SQL. I don't want to implement sending periodic notifications to all users.
Before I go down the path of developing for the iOS background sync, I needed to do some due diligence and research alternatives to iOS's background sync and didn't find anything.
Has anyone seen or developed an alternative to iOS's background sync or dealt with this issue for their enterprise apps?
As an enterprise app there's nothing extra you can do except that you can use whatever background modes you want (audio, location, voip etc,) without needing to have a legitimate reason to do so.
Where this might assist is:
you could make use of a significant location change (as opposed to a regular location change) notification to run your app in the background. The problem with this is it of course depends on the user of your app to move around. However, assuming everybody in your workforce commutes to/from work with their iPhone then you would have two opportunities each day for the app to run in the background. A app run due to a location change can be made to execute in the background for more than 30 seconds.
voip pushes: Unlike a regular push notification, a voip push will launch the app even if the user has force terminated it. To make use of this functionality is only a tiny bit more effort than using regular push, you don't have to do anything regarding making or receiving an actual voip call, you just need the voip capability and voip certificates instead of normal push certificates.
The comment in that link is not correct regarding force quitting and background fetch - a user force quitting an app does not make it ineligible to run for a background fetch, I have force quit my own app that uses background fetch but it will still be started by the OS, however what will happen is that the frequency when the app is run will decrease lots, and if the user never runs the app again then the OS will stop launching it.
A user force quitting an app will prevent other things from happening, such as it running in the background in response to a silent push notification for example (unless its a voip push).
Also the 30 seconds in not related to download times, NSURLConnection would stop after 30 seconds, NSURLSession is designed to continue to download on your app's behalf. But if you are downloading and then applying lengthy SQL processing it would be an issue. But minutes of processing time seems excessive, are you sure its all optimized?
The goal is to be able to retrieve data from our servers periodically when app is suspended/not running
The only reliable way to achieve such a behaviour is implementing a User-facing Remote (Push) Notifications framework on backend & apps.
You can append 4kB (or 5 for VOIP) worth of data in the push JSON payload, eliminating need for a network fetch request if implemented in a handshake mechanism.
You can evaluate usage on Silent Remote Notifications to augment content updation & fetch small amounts of content opportunistically, though it has the same as Background App Refresh.
You can definitely improve the API that can take minutes due to long running SQL
And remember you need to have the app updated only when the user actually fires it up. Evaluate implementing a catchy & smooth fetching content screen that transitions into the actual screens once all data is fetched.

iOS Enterprise app - How can I make sure my app runs in the background?

First of all it's important to note that I'm developing an Enterprise App, so there is no need for App Store guidelines \ approvals considerations.
My goal is the following:
1) An iPhone app which the user should open only one time only. During this one time he will go through some sign up process.
2) Once step (1) has finished (either by app suspension or app close), the app should "wake up" every hour (more or less) and send the server some data regarding the user from the background (all is done with the user agreement of course).
Optional Solutions I tried:
I read very thoroughly Apple guidelines for running in background in https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
I decided to go with 2 UIBackgroundModes:
location
fetch
1) For location I use:
startMonitoringSignificantLocationChanges();
manager.requestAlwaysAuthorization()
In order to make sure my app will run after "app close" or even "device reboot" I had to use both options. See Apple guidelines:
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW1
If you leave the significant-change location service running and your
iOS app is subsequently suspended or terminated, the service
automatically wakes up your app when new location data arrives.
2) For background fetch I use
performFetchWithCompletionHandler()
and
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum);
For some reason the app doesn't run in background after 24 hours. Meaning the app never "wakes up" again even though according to Apple guidelines whenever significant location update occurs - it suppose to wake up.
What can I do in order to guarantee as much as possible that my app will run regularly in the background?
In your project properties you have to allow background mode for your application to Update location and for background fetch.
Fetch in background is not so easy as it seems.
iOS will define by itself how often it will fetch data in background modeeven you set option for each 15 minutes :(
As my practice shows time interval for fetching new data is less if user open application from time to time so iOS makes some calculations about normal app use. As a result app calls background fetch data according to app ussage.
But you can make one trick:
you can call fetch procedure from you location procedure. For data exchange it was usefull in my projects :)
The solution worked with Silent PN.
My goal as noted in the bounty was: ".. to have an iOS app that runs regularly in the background for 30+ days when not opened at all. Should also run after the app closes."
I found that when sending PN with "content-available" : 1 did the trick for me.
I set up a server which sends every 15 min a "silent PN" to all registered devices. I was able to confirm from the same server that those clients receive the PN and act on it.
Thanks #andlin for the advice.

Where and When to get data for Watch Complication

After working with complications for a few days, I feel confident saying the following about the update process for updates that happen at a prescribed interval:
The system calls requestedUpdateDidBegin()
This is where you can determine if your data has changed. If it hasn't, your app doesn't have to do anything. If your data has changed, you need to call either:
reloadTimelineForComplication if all your data needs to be reset.
extendTimelineForComplication if you only need to add new items to the end of the complication timeline.
Note: the system may actually call requestedUpdateBudgetExhausted() instead of requestedUpdateDidBegin() if you've spent too much of your complication's time budget for the day. This is the reason for this question.
If you called reloadTimelineForComplication, the system will call getCurrentTimelineEntryForComplication (along with the future and past variants that get arrays, depending on your time travel settings)
This is conjecture as I haven't tested it yet, but I believe if you called extendTimelineForComplication that only the getTimelineEntriesForComplication(... afterDate date: NSDate ...) would be called.
The system will then call getNextRequestedUpdateDateWithHandler so you can specify how long until your complication requires a new update.
Apple's documentation is quite clear that you should not ask for updates too often, or conduct too much processing in the complication code or you will exhaust your time budget and your complication will stop updating. So, my question is: where and when do you do the update?
For context, my scenario is a URL with return data that changes up to two times per hour.
The most obvious place in which to put the URL fetch code is func requestedUpdateDidBegin() Fetch the data, store it, and if there's no change, just return. If there was a change then extend or reload the timeline.
However, a URL fetch can be costly. Alternatives:
Put the code on the phone app and send it over with a WCSession, but if the user closes that app then the updates will no longer happen.
Use push updates, but this isn't a web app, so I have no place to send them from.
Obviously I will update all the data when the user interacts with the watch app, but that now means it only gets updated when the user uses the app, which negates the need for a complication.
Is there anywhere else? Can I have a periodic function in the watch app that isn't part of the complication? Where is the right place to fetch the data for a complication update?
For watchOS 3, Apple recommends that you switch from using the complication datasource getNextRequestedUpdateDate scheduled update to update your complication.
The old way for watchOS 2
requestedUpdateDidBegin() is really only designed to update the complication. Keeping your complication (and watch app) up to date usually involves far more than reloading the timeline (and asynchronously retrieving data never fit in well with the old approach).
The new way for watchOS 3
The new and better approach is to use background refresh app tasks. You can use a series of background tasks to schedule and handle your app extension being woken in the background to:
Fetch new data
using WKWatchConnectivityRefreshBackgroundTask to obtain data from the phone, or
using WKURLSessionRefreshBackgroundTask to download data from a server
update your model once the data arrives,
update your complication from the model (by reloading or extending the timeline), and finally
update your app's dock snapshot to show the data on the dock
Call each tasks’s setTaskCompleted method as soon as the task is complete.
Other benefits of using app tasks
One of the key features about this design is that the watch extension can now handle a variety of foreground and background scenarios which cover:
initially loading data when your app/complication starts,
updating data in the background, when the extension is woken by a background task, and
updating data in the foreground, when the user resumes your app from the dock.
Apple recommends that you use each opportunity you are given regardless of whether your app is in the foreground or background to keep your complication, app, and dock snapshot up to date.
Are there any limitations?
The number of total available tasks per day is divided among the number of apps in the dock. The fewer apps in the dock, the more tasks your app could utilize. The more apps in the dock, the fewer you can utilize.
If your complication is active, your app can be woken up at least four times an hour.
If your complication is not active, your app is guaranteed to be woken at least once an hour.
Since your app is now running in the background, you're expected to efficiently and quickly complete your background tasks.
Background tasks are limited by the amount of CPU time and CPU usage allowed them. If you exceed the CPU time (or use more than 10% of the CPU while in the background), the system will terminate your app (resulting in a crash).
For more information
A good introduction explaining when and why to update your watch app is covered in Designing Great Apple Watch Experiences.
For specifics, the Keeping Your Watch App Up to Date session covers everything you need to know to keep your complication, app, and dock snapshot up to date.
WatchBackgroundRefresh sample code demonstrates how to use WKRefreshBackgroundTask to update WatchKit apps in the background.
Edit: El Tea (op) has posted a good answer at https://stackoverflow.com/a/32994055/630614
This is an interesting question/problem, and I've been wondering about a lot of the same!
For the most part, it seems that when I'm working on a new complication I need to step back and see when I really want to update it. A "countdown" complication could set all future timeline entries at one time, when the "end date" is set. An app that shows the current status of a web service could have relevant data stored in NSUserDefaults when an APNS comes through.
If you don't have access to APNS, don't want to run your iOS app in a background mode, and don't want to make HTTP requests from Apple Watch, I can think of 2 other options.
1) Schedule local notifications. The good part is that your Apple Watch should run didReceiveLocalNotification, but the bad part is that the user will get a notification when you're simply trying to check the status without a disruption.
2) Send a message to iOS via sendMessage(_:replyHandler:errorHandler:) in your reloadTimelineForComplication method, setting nil for the replyHandler to make it as quick as possible:
Calling this method from your WatchKit extension while it is active and running wakes up the corresponding iOS app in the background and makes it reachable.
Your iOS app could perform whatever network requests are needed and then store the information or push it to Apple Watch. Unfortunately, I don't think the watch extension will have it's session.didReceive... called until you run it, but you could access the data on the next call to requestedUpdateDidBegin.
As I said, I'm very interested in this same thing, so post some thoughts back and maybe we can extrapolate on some best practices here.

Is there a way to set an iOS app to automatically download data every night?

We have a customer who wants us to have our iOS app check for new data posted every night and download it if it is available. As far as I can tell this is only possible if the app is already open or if they have someone physically accept a notification or initiate the process themselves.
Is this correct? I can't imagine Apple wanting to allow launching of an app and downloading data with no user interaction at all.
Yes, generally you can only download data at exactly specified times if the app is actually running in the foreground, that is correct. It wouldn't matter if the app was open already or the user opened it from a notification, the point is that user interaction is required. So, the client can't have exactly what they want.
Look at background downloading (fetch) from iOS7+ where you can register the app to perform background downloading in advance of usage. iOS is fully in control of this and it may choose to run the app and it may not. iOS will monitor when your app is usually used by a particular user and, if appropriate, it will allow the app to run in the background to do some downloading before the user is expected to use the app.
In particular you're looking at setMinimumBackgroundFetchInterval: and setting the UIBackgroundModes key with to fetch in the Info.plist.
As an aside, here's an idea based on your expanded information:
Use idleTimerDisabled to prevent the app from sleeping during main usage and keep a track of the time
After the main usage period of the app is over, start your downloads
After the downloads are done allow the screen to sleep
On the next day, if a user opens the app, repeat
It isn't perfect, but it's an approximation

How do iOS chat apps keep running in the background?

I have always coded for Android, and now I'm looking to expand my knowledge to iOS development; so I'm really new at this, please be patient.
I understand that only a small group of apps are allowed to run indefinitely in the background. Those are VoIP, Music players and location tracking apps.
I want to write a chat app using the XMPP framework. Everything is fine until the user puts the app in the background, in which case, the app will stay connected for about ten minutes to then be killed by the system and therefore the user won't be able to receive new messages.
I am aware of hacks to keep the app alive. Hacks such as defining it as a music playing app in the info.plist file and then just play some empty sound indefinitely. But I'm also aware that Apple will reject the app when it's time to publish to the App Store.
So, normally, how do other apps do it? How can other chat apps stay alive in the background to receive new messages from the servers? Apps like Google Hangouts, IM+ and such?
Ideally, they aren't really running in the background, but use push notifications, as others have mentioned.
But some chat clients seem to do something else: I've verified (by sniffing the traffic of an idle iOS device) that at least Google Hangouts, Facebook and Skype all keep a persistent socket opened in the background, and regularly send traffic to keep it alive.
I'm suspecting that they are using the VoIP exceptions to Apple's otherwise strict background execution policies. iOS allows "VoIP apps" to run in the background and keep one socket open to be notified about incoming calls and messages.
Maybe they are also using the new "background fetch" feature of iOS 7, but as far as I know, that doesn't allow persistent socket connections.
The iOS operating system allows for the existence of something called a PUSH NOTIFICATION
There exists hundreds of tutorials online which teach you how to implement the notification code and how to respond accordingly when you receive such a message!
http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
Check this link out for an in-depth tutorial on push notifications!
http://maniacdev.com/2011/05/tutorial-ios-push-notification-services-for-beginners
I think most of these apps use push notifications and just load the last messages from the server as soon as the app is being opened.
While there are some hacks, and your app can ask for more time when it goes in background (up to a point, and with no guarantees), this is a perfect application for push notifications.
The server tells the phone there's a message, and iOS wakes your app up to process it.
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html
As of iOS 7 there is a new background-execution mode - 'fetch' for apps that need to periodically fetch new data. It sounds like your case would meet that definition.
You can find the information in the iOS App Programming Guide -
Fetching Small Amounts of Content Regularly
In iOS 7 and later, an app that retrieves content regularly from the
network can ask the system for background execution time to check for
new content. You enable support for background fetches from the
Background modes section of the Capabilities tab in your Xcode
project. (You can also enable this support by including the
UIBackgroundModes key with the fetch value in your app’s Info.plist
file.) At appropriate times, the system gives background execution
time to the apps that support this background mode, launching the app
directly into the background if needed. The app object calls the
application:performFetchWithCompletionHandler: method of its app
delegate to let you know when execution time is available.
You can also use push notifications, but that requires some server infrastructure
An app running in the background has limited capability. Read App States and Multitasking thoroughly to decide how best to design your app. Chat is not listed as one of the specific exceptions that can operate with a more relaxed policy. You will never be able to "keep [your] app live in background forever." You might be able to leverage an iOS 7 feature also described in this guide, Fetching Small Amounts of Content Regularly.
iOS App Programming Guide: App States and Multitasking
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOS ProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html

Resources