kodeco.com Forums

Background Modes Tutorial: Getting Started

Get your iOS Swift apps working with the most common background modes: audio playback, location updates, general finite-length tasks, and background fetch.

This is a companion discussion topic for the original entry at http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial

Background Fetch works perfectly. Thanks

1 Like

Very good tutorial. But I would like to ask for Performing Finite-Length Tasks… or, Whatever subject.

How can I give limit for position. For example I would like to say. "stop after 5


Thanks for the question. It is a good point. You can just call endBackgroundTask which in turn calls UIApplication.sharedApplication().endBackgroundTask(backgroundTask) and invalidates the task.

In that case the expiration handler won’t be called but just in case there is a race you might want to guard against that by noting the state of the backgroundTask variable and only ending if it is valid.

Excellent tutorial! Cleared a lot of question i had about background modes.

I am building an app which requires the users current location every 30 mins and post the location update to the server and schedule a local notification with the response received from the server.

How would you advise to go about this since NSTimer doesn’t run when the app is suspended and the background execution limit is about 3 mins.

Would really appreciate any help in leading me in the right direction.

Thanks! It is an interesting problem that would require some experimentation. Every release iOS seems to get more opportunistic about when to use the battery.

You are right that you can’t achieve that with an NSTimer. From iOS 8 there is a new check-in location mode that you can get a callback overtime the location changes. That might be what you are looking for? (You can find it in the WWDC video WWDC14 - Videos - Apple Developer )

If it turns out that you really need the app to wake up every 30 minutes, I think the only way to do it would be to send a silent notification from a server and perform some processing and potentially turn it into a “loud” local notification. However, even those are not guaranteed to deliver so you probably can’t use that if it is something super mission critical.

The playing silence trick would probably work but won’t win you any friends and probably would be rejected in app review. Any other ideas out there?

Any idea why my NSLog prints a number beyond 100 digits when It prints the backgroundTimeRemaining? Can’t be possible that I have months of background time available! Thanks

Great tutorial,

Be aware that for iOS 9, to be able to Receiving Location Updates you have to allowsBackgroundLocationUpdates variable set to true

var manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
if #available(iOS 9.0, *){
    manager.allowsBackgroundLocationUpdates = true

More information there : iOS background mode location update - manager doesn’t update in background mode

If it turns out that you really need the app to wake up every 30 minutes, I think the only way to do it would be to send a silent notification from a server and perform some processing and potentially turn it into a “loud” local notification.

I liked the tutorial.I have question is there any possibility to trigger an app event when its not even running in the background? I mean that he never open the app but i want to back webservice call. I have tried with background fetch but its working when app is kept in the background.

Question 2
Consider the same scenario where app is not running at all and I want to awake the app with significant location and record location data. I was able to do it but its taking lot of time. some times more than 4kms to start recording. Is there a better solution?

Great Tutorial , I have a question :

I am trying to create a local notification with the following requirements:

-The user selects what time of the day he would like to receive the notification for example :
between 8:00 AM and 9:00 AM
-The message contained in the notification requires calling an API to get an updated content.

I was able to create the Local Notification, but my problem is once my app is in the background, the API call is not made anymore and the Notifications stop too

In my case I would need to make an API Call every 15 minutes, while my App is in the background, do the API Call then send a local notification with the new data

i tried the location updates.
its stop after 15Min in background.
is there any way to keep the location updates forever? (until the app will enter forground)?

great tutorial! thank you! I have a question related to what can be done in the background with the new (ios 9) photo framework. i’d like to keep observing for changes to the photo library and send the meta-data of such changes to a server. Is that something that can be done as a background process? Thank you in advance!

I have several GPS apps all of which allow third-party devices such as the Dual 150 and 160 GPS receivers as well as Apple’s built-in GPS receiver. Since continuous distance measurements are critical down to 5 feet or less when driving either fast or slow, I force the apps to require background modes for Location Updates, External Accessory Communication, and Uses Bluetooth LE Accessories.

In addition to computing distances at sampling rates ranging from 1 to 10 times per second, I also use MKOverlayRenderer and MKPolyline on a mapView to display the track on a map whenever the car has moved to a new location.

I am using Xcode 8.1 and iOS 10.1 for testing on iPhones and iPads. Everything works as expected on the Simulator, but on the iPhone and iPad devices themselves, the Apple GPS background signals are not updating while the Dual GPS background signals are fine. The foreground functioning is the same and accurate, however.

Strangely, background mode works perfectly with the Dual GPS Receivers in the real world but fails spectacularly when having to rely on Apple’s GPS receiver. When the apps are active, again in the real world, the distances and the tracking are perfectly computed and displayed whether using the Duals or the Apple internal GPS.

When using the Apple GPS the track and distance show properly, then I touch the home button and put the app into background mode for a short while. When I return to active mode, the distance is too short and the track shows as a straight line from the point at which I entered background mode to the point where the app returns to active mode.

Needless to say, I expect the background location distances and tracking to work regardless of whether the iPhone or iPad is using Apple’s GPS or some third-party input. But, clearly that is not the case.

Is there some problem with background location when both distance and rendering are demanded by the app? If so, why should it work correctly with a third-party device but not with Apple’s own built-in GPS device. Very, very strange.

Any ideas would be most appreciated. Thanks.

Here is some of my code:

  • (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.allowsBackgroundLocationUpdates = YES;
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;

    if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [_locationManager requestAlwaysAuthorization]; }

I downladed source code from this tutorial , start on my IPhone 6 but Background Fetch never tirgers , why?

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]