Skip to content

Geofencing service

Davor Komušanac edited this page Dec 5, 2022 · 42 revisions

Geofencing service allows you to establish a virtual fence around a predefined geographic area. When one of your app users enters or exits the area, you can set your app to push a message to the user. Infobip IP Messaging Platform supports geolocation based campaigns. This guide explains how you can easily setup your iOS application to support geolocation-based campaigns.

Configuring project for using geofencing services

Include NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription keys in your app’s Info.plist. These keys let you describe the reason your app accesses the user’s location information. The system includes the value of these keys in the alert panel displayed to the user when requesting permission to use location services.

Important:

For iOS 11 compatibility you are additionally required to include the NSLocationAlwaysAndWhenInUseUsageDescription key in your app's Info.plist file. If this key is not present, authorization requests fail immediately (Documentation).

Installation

In order to install Geofencing service, declare an additional dependency in you podfile:

pod 'MobileMessaging/Geofencing'

and perform pod update command from the Terminal.

Usage

MobileMessaging SDK has geofencing service disabled by default.

Enabling the Geofencing service

In order to enable the Geofencing service, use the withGeofencingService() factory method in addition to your MobileMessaging initialization chain:

// Swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    MobileMessaging
        .withApplicationCode(<#your application code#>, notificationType: <#for example MMUserNotificationType(options: [.alert, .sound])#>)?
        ...
        .withGeofencingService()?
        ...
        .start()
    ...
}   
expand to see Objective-C code

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[[MobileMessaging withApplicationCode: <#your application code#> notificationType: <#your preferred MMUserNotificationType#>]
        withGeofencingService]
        start:nil];
    ...
}

In this case, Geofencing service starts up after the MobileMessaging is started and the service will automatically prompt user for permissions for the app to use iOS Location Services. The “Always” authorization level is requested by default for the sake of better monitoring accuracy.

Custom initialization and startup flow

In case you want to change the default authorization level or to implement your own initialization and launching flow the Geofencing service has a convenient API:

// Swift
MobileMessaging.geofencingService.authorize(.WhenInUse) { capabilityStatus in
    switch capabilityStatus {
    case .Authorized:
        // user has authorized the service, you are free to start using it
        MobileMessaging.geofencingService.start()
    case .Denied:
        // user denied the access for Location Service, you can try to talk him out of it :)
    case .NotAvailable:
        // the service is not available on the device, there is nothing you can do
    case .NotDetermined:
        break // a fairly unlikely scenario
    }
}
expand to see Objective-C code

[[MobileMessaging geofencingService] authorize: MMLocationServiceUsageWhenInUse completion:^(enum MMCapabilityStatus capabilityStatus) {
    switch (capabilityStatus) {
        case MMCapabilityStatusAuthorized:
            // user has authorized the service, you are free to start using it
            [[MobileMessaging geofencingService] start: nil];
            break;
        case MMCapabilityStatusDenied:
            // user denied the access for Location Service, you can try to talk him out of it :) #>
            break;
        case MMCapabilityStatusNotAvailable:
            // the service is not available on the device, there is nothing you can do #>
            break;
        case MMCapabilityStatusNotDetermined:
            // a fairly unlikely scenario
            break;
    }
}];

Once user grants permissions for your application to use location services, the Geofencing service starts automatically.

In order to stop the service:

// Swift
MobileMessaging.geofencingService.stop()
expand to see Objective-C code

[[MobileMessaging geofencingService] stop];

Handle region entered event

In order to be notified about the region entered event you can subscribe to MMNotificationGeographicalRegionDidEnter:

//Swift
NotificationCenter.default.addObserver(self,
                                     selector: #selector(self.geographicalRegionEntered(_:)),
                                     name: NSNotification.Name(rawValue: MMNotificationGeographicalRegionDidEnter),
                                     object: nil)
expand to see Objective-C code

// Objective-C
[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(geographicalRegionEntered:)
                                             name: MMNotificationGeographicalRegionDidEnter
                                           object: nil];

The NSNotification object will contain the information about the region:

// Swift
@objc func geographicalRegionEntered(_ notification: NSNotification) {
    guard let region = notification.userInfo?[MMNotificationKeyGeographicalRegion] as? MMRegion else
    {
        return
    }
    print("Region entered: \(region)")
    <# handle the event the way you like #>
}
expand to see Objective-C code

// Objective-C
-(void)geographicalRegionEntered:(NSNotification *)notification {
    MMRegion * region = notification.userInfo[MMNotificationKeyGeographicalRegion];
    NSLog(@"Region entered: %@", region);
    <# handle the event the way you like #>
}

If the region was entered successfully and the corresponding region message was shown to the user, a MMNotificationMessageReceived event is emitted. Learn more how to handle this event.

Clone this wiki locally