iOS Tutorial Background location tracking

iLocation library allows you to track the device location when your app is in the foreground.

Using the code posted in this tutorial you can mark your app as a special kind of app that requires background location updates and then your app will continue to run in the background and receive location updates until you call LocationManager.Stop or until the user kills the app.

Apple's documentation: https://developer.apple.com/library...n.html#//apple_ref/doc/uid/TP40009497-CH2-SW3

The first step is to mark the app for background execution:
B4X:
#PlistExtra: <key>UIBackgroundModes</key><array><string>location</string></array>
We also need to describe the reason for the location usage:
B4X:
#PlistExtra:<key>NSLocationAlwaysUsageDescription</key><string>Track your location in the background for better ad revenue.</string>
#PlistExtra:<key>NSLocationUsageDescription</key><string>Used to display the current navigation data.</string>
On iOS 7 the NSLocationUsageDescription string will be used. On iOS 8+ the NSLocationAlwaysUsageDescription string will be used. This replaces the standard NSLocationWhenInUseUsageDescription string. Make sure to update the strings as needed.

Two additional changes:
1. You need to call StartBackground sub instead of Location.Start
2. (optional) Call AllowPauseLocationAutomatically sub and set the activity sub. The OS will use this information to pause the location updates when the location is not expected to change.
You can read more about the activities types: https://developer.apple.com/library.../index.html#//apple_ref/c/tdef/CLActivityType

Edit: It is recommended to disable the AllowPauseLocationAutomatically as explained in post #10.

See the code in the attached project.
Note that the debugger will eventually disconnect when the app is in the background.

Edit: September 2018 - Added new required usage key:
B4X:
#PlistExtra:<key>NSLocationAlwaysAndWhenInUseUsageDescription</key><string>Track your location in the background for better ad revenue.</string>
 

Attachments

  • BackgroundLocation.zip
    2.6 KB · Views: 928
Last edited:

schimanski

Well-Known Member
Licensed User
Longtime User
I used the attached example to write the data to a file. I have tested it in release several times, but the file is only updated, if the app is in the forground...Am i missing something?
 

Attachments

  • 1.zip
    1.2 KB · Views: 553

Erel

B4X founder
Staff member
Licensed User
Longtime User
The code in the first post was updated. The StartBackground sub should be:
B4X:
Sub StartBackground(lm As LocationManager, MinimumDistance As Double)
   Dim no As NativeObject = lm
   no = no.GetField("manager")
   If App.OSVersion >= 8 Then
     no.RunMethod("requestAlwaysAuthorization", Null)
   End If
   If App.OSVersion >= 9 Then '<--- new requirement in iOS 9
     no.RunMethod("setAllowsBackgroundLocationUpdates:", Array(True))
   End If
   no.SetField("distanceFilter", MinimumDistance)
   no.RunMethod("startUpdatingLocation", Null)
End Sub
 

Baris Karadeniz

Active Member
Licensed User
How can I give permission to app to update location (foreground and background) with a button in the app? Like "Tracking Start/Stop" I don't want that there will be question when the app starts.

It is enough to initialize and stop LocManager with this button or do I have to initialize and stop "StartBackground" too?
 

Baris Karadeniz

Active Member
Licensed User
I am asking about authorization question when the app begins to run. Can I give authorization with button (Tracking Start/Stop)?
 

Baris Karadeniz

Active Member
Licensed User
I mean I don't want that "authorization dialog" is shown. When the App run, if user press on the Tracking start button authorization will be given without showing the authorization dialog. Is it possible?
 

Utopians

New Member
Licensed User
i change

#PlistExtra:<key>NSLocationWhenInUseUsageDescription</key><string>Used to display the current navigation data.</string>

to

#PlistExtra:<key>NSLocationAlwaysUsageDescription</key><string>Used to display the current navigation data.</string>


not shown "Latloon is Using Your Location". (app is background)

:)
 
Last edited:

fbritop

Active Member
Licensed User
Longtime User
Erel,
When I use:

B4X:
    If App.OSVersion >= 9 Then
        no.RunMethod("setAllowsBackgroundLocationUpdates:", Array(True))
    End If

it breaks with: Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)

I have no clue about this error, where should I look for?

Thanks
FBP
 

fbritop

Active Member
Licensed User
Longtime User
Mine is running on ios version 9 and it does not work. There has been no changes to the original code
 

fbritop

Active Member
Licensed User
Longtime User
B4X:
Sub StartBackground(lm2 As LocationManager, MinimumDistance As Double)
   
    Dim no As NativeObject = lm2
    no = no.GetField("manager")
    no.SetField("pausesLocationUpdatesAutomatically", False)
   
    If App.OSVersion >= 8 Then
        no.RunMethod("requestAlwaysAuthorization", Null)
    End If
       'If App.OSVersion >= 9 Then '<--- new requirement in iOS 9
    '    no.RunMethod("setAllowsBackgroundLocationUpdates", Array(True))
       'End If   
    'no.SetField("distanceFilter", 1)
    'no.SetField("pausesLocationUpdatesAutomatically", False)
    'no.SetField("startMonitoringSignificantLocationChanges", False)
    'no.RunMethod("startUpdatingLocation", Null)

    If App.OSVersion >= 9 Then
        no.RunMethod("setAllowsBackgroundLocationUpdates:", Array(True))
    End If
    no.SetField("distanceFilter", MinimumDistance)
    no.RunMethod("startUpdatingLocation", Null)
       
   
End Sub

LOGS:

B4X:
*** Assertion failure in -[CLLocationManager setAllowsBackgroundLocationUpdates:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreLocationFramework/CoreLocation-1861.3.25.50/Framework/CoreLocation/CLLocationManager.m:609
Error occurred on line: 149 (Main)
Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)
Stack Trace: (
  CoreFoundation       <redacted> + 150
  libobjc.A.dylib      objc_exception_throw + 38
  CoreFoundation       <redacted> + 0
  Foundation           <redacted> + 92
  CoreLocation         CLClientGetCapabilities + 9024
  CoreFoundation       <redacted> + 68
  CoreFoundation       <redacted> + 292
  LlaveMovil.com       +[B4I runDynamicMethod:method:throwErrorIfMissing:args:] + 1780
  LlaveMovil.com       -[B4INativeObject RunMethod::] + 158
  LlaveMovil.com       -[b4i_main _startbackground::] + 2882
LlaveMovil.com       -[b4i_main _starttrack] + 630
CoreFoundation       <redacted> + 68
CoreFoundation       <redacted> + 292
LlaveMovil.com       +[B4I runDynamicMethod:method:throwErrorIfMissing:args:] + 1780
LlaveMovil.com       -[B4IShell runMethod:] + 574
LlaveMovil.com       -[B4IShell raiseEventImpl:method:args::] + 1998
LlaveMovil.com       -[B4IShellBI raiseEvent:event:params:] + 1442
LlaveMovil.com       __33-[B4I raiseUIEvent:event:params:]_block_invoke + 74
libdispatch.dylib    <redacted> + 10
libdispatch.dylib    <redacted> + 22
libdispatch.dylib    <redacted> + 1524
CoreFoundation       <redacted> + 8
CoreFoundation       <redacted> + 1574
CoreFoundation       CFRunLoopRunSpecific + 520
CoreFoundation       CFRunLoopRunInMode + 108
GraphicsServices     GSEventRunModal + 160
UIKit                UIApplicationMain + 144
LlaveMovil.com       main + 108
libdyld.dylib        <redacted> + 2
)
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Are you sure that these three lines are included in your code:
B4X:
#PlistExtra:<key>NSLocationAlwaysUsageDescription</key><string>Track your location in the background for better ad revenue.</string>
#PlistExtra:<key>NSLocationUsageDescription</key><string>Used to display the current navigation data.</string>
   #PlistExtra: <key>UIBackgroundModes</key><array><string>location</string></array>

You will get this error if they are missing.

Are you testing it on a real device?
 
Top