What you will learn

This step-by-step tutorial will teach you how to create your first Custom Alert Strategy, by extending the BeaconAlertStrategy object.

You will code a TimeAlertStrategy: this strategy will allow you to trigger an alert associated to a beacon, if the beacon is detected by a smartphone for 60 seconds or more.

Pre-requisites - What you need to get started

  • Your SDK credentials, including an SDK Login, Password, and Company Key to initialize the SDK.
  • A BLE beacon, which has been configured on your account, in order to test interactions with your app.
  • An iOS Device, with Bluetooth 4.0 and iOs 8 and above.
  • The Xcode application, which you can download from the App store.
  • You must have read the alert process tutorial and completed the alert tutorial

Two ways to code a Beacon Alert Strategy

There are two ways you can code a Beacon Alert Strategy:

  • Option #1 - Implementing the ATBeaconAlertStrategyDelegate interface: The ATBeaconAlertStrategyDelegate allows you to implement the complete strategy process, giving you control over the beacon objects but implying that you maintain their lifecycle (initializations, updates...).

  • Option #2 - Extending the ATBeaconAlertStrategy object: Extending the BeaconAlertStrategy object saves you time because you extend a source code base that already manages the initialization and update processes.

Because the latter fits the majority of needs, this tutorial will essentially focus on Option #2. Nevertheless, you can find an implementation for Option #1 in the source code for this tutorial (called TimeAlertStrategyFirstWay).

About the SDK model

Overview of the ATBeaconAlertStrategyDelegate interface

Prior to discussing implementation, let's take a deeper look at the methods of this interface.

@required
-(void) updateBeaconContent:(ATBeaconContent *) _beaconContent;

@optional
-(Class) getBeaconAlertParameterClass;

-(NSString *) getKey;

-(bool) isConditionValid:(ATBeaconAlertParameter *) _beaconParameter;

-(bool) isReadyForAction:(ATBeaconAlertParameter *) _beaconParameter;

Let's take a quick look at each one:

@required
-(void) updateBeaconContent:(ATBeaconContent *) _beaconContent;
  • This method is called every time a beacon range scan is occurring (as a reminder, this only happens if the alert listener has been registered), and updates the Beacon Alert Strategy Parameter object associated to the Beacon Content object.
@optional
-(Class) getBeaconAlertParameterClass;
  • This method will permit to create the correct Beacon Alert Parameter for the Beacon Alert Strategy
-(NSString *) getKey;
  • This method returns the String Key associated to the Alert Strategy that was created
  • You must add this key to the appropriate custom alert field on the Adtag platform
-(bool) isConditionValid:(ATBeaconAlertParameter *) _beaconParameter;
  • This method returns true if the conditions to display an alert are met.
-(bool) isReadyForAction:(ATBeaconAlertParameter *) _beaconParameter;
  • This method returns true if an alert can be triggered on this beacon.

Overview of the ATBeaconAlertStrategy object

The ATBeaconAlertStrategy object is an abstract class that implements most of the ATBeaconAlertStrategyDelegate methods.

The ATBeaconAlertStrategy object implements the following methods by default:

  • updateBeaconContent
  • getBeaconAlertParameterClass: returns a BeaconAlertParameter class as default.
  • isReadyForAction: returns true if the isConditionValid parameter is set to true, and the actionStatus parameter is at Waiting For Action.

You also have to manually implement the three following additional methods:

  • getStrategyKey: from the ATBeaconAlertStrategyDelegate
  • updateAlertParameter: allows to update the ATBeaconAlertParameter object associated to a beacon.
    • The ATBeaconAlertStrategy calls this method before the isConditionValid method
    • this means the ATBeaconAlertParameter object transmitted to the isConditionValid method is up to date.
  • isConditionValid: from the ATBeaconAlertStrategyDelegate

The ATBeaconAlertStrategy object comes with a constructor with one paremeter : maxTimeBeforeReset

[[ATBeaconAlertStrategy alloc]initWithMaxTime:60000]

The maxTimeBeforeReset parameter allows to determine how long after the beacon stops being detected, the actionStatus parameter is automatically reset to Waiting for Action.

Note:

If necessary, you can override the 3 default methods of the ATBeaconAlertStrategyDelegate interface.

Step 1: Clone the sdk-tutorial repository

  • Clone the sdk-tutorial repository
git clone https://github.com/opsct/sdk-tutorial.git

objectiveC:

  • Open the sdk-tutorial>ios>ObjectiveC>Beacon>7-Alert-Strategy>Starter folder

SWIFT:

  • Open the sdk-tutorial>ios>SWIFT>Beacon>7-Alert-Strategy>Starter folder

Step 2: Configure the SDK

  • Configure your CocoaPod files and .plist
  • Configure your SDK with:
    • the UUID of your beacon
    • the appropriate Adtag Environment (DEMO / PREPROD / PROD / PROD_US)
    • your SDK credentials
    [[[ATAdtagInitializer sharedInstance] configureUrlType:ATUrlTypeProd andLogin:@"__USER__" andPassword:@"__PSWD__" andCompany:@"__COMPANY__"] synchronize];

If you need more informations, have a look to the 5 minutes quickstart tutorial

Step 3: Create a TimeAlertStrategyParameter object

The TimeAlertStrategyParameter object extends the ATBeaconAlertParameter object.

The ATBeaconAlertParameter object synchronizes and centralizes all of the information regarding a specific beacon and associated alerts. For more information, please read the alert process tutorial.

The TimeAlertStrategyParameter allows to save two additional parameters:

  • timeToShowAlert: indicates the time when the application can start to display an alert
  • lastDetectionTime: indicates the last time the beacon was detected by a smartphone

Now let's start coding the TimeAlertStrategyParameter:

  • Create a TimeAlertStrategyParameter object that extends the ATBeaconAlertParameter object.
#import <UIKit/UIKit.h>
#import <ATConnectionHttp/ATConnectionHttp.h>

@interface TimeAlertStrategyParameter : ATBeaconAlertParameter

@end
  • Add the timeToShowAlert and lastDetectionTime parameters
@interface TimeAlertStrategyParameter : ATBeaconAlertParameter{
    
    double lastDetectionTime;
    
    double timeToShowAlert;
}

@property double lastDetectionTime;

@property double timeToShowAlert;

@end

Step 4: Create an AlertTimerStrategySecondWay class

  • Create a AlertTimerStrategySecondWay class that extends the ATBeaconAlertStrategy class:
#import <ATLocationBeacon/ATLocationBeacon.h>
#import <ATConnectionHttp/ATConnectionHttp.h>
#import <Foundation/Foundation.h>

@interface AlertTimerStrategySecondWay : ATBeaconAlertStrategy 
{
    double delayBeforeCreatingAlert;
}
@property double delayBeforeCreatingAlert;

- (id)initWithMaxTime:(int)_maxTimeBeforeReset
delayBeforeCreatingAlert:(int)_delayBeforeCreatingAlert;

@end
  • Add a constructor that allows to define the amount of time a beacon must be detected by the smartphone before triggering an alert
#import "AlertTimerStrategySecondWay.h"
#import "TimeAlertStrategyParameter.h"

@implementation AlertTimerStrategySecondWay
@synthesize delayBeforeCreatingAlert;


- (id)initWithMaxTime:(int)_maxTimeBeforeReset
delayBeforeCreatingAlert:(int)_delayBeforeCreatingAlert{
    self = [super initWithMaxTime:_maxTimeBeforeReset];
    if (self) {
        self.delayBeforeCreatingAlert = ((double) _delayBeforeCreatingAlert / 1000.0);
    }
    return self;
}

@end
  • Override the getBeaconAlertParameterClass method to initialize a TimeAlertStrategyParameter in association with a dedicated beacon and this strategy
-(Class) getBeaconAlertParameterClass {
    return [TimeAlertStrategyParameter class];
}
  • Define the key for the strategy:
-(NSString *) getKey{
    return @"timeAlertStrategy";
}

Note:

This key will enable you to associate the strategy to a beacon on the Adtag Platform, using the 'Your custom strategy' field. Learn more in "Updating the alert content on the Adtag platform".

  • Update the timeToShowAlert and the lastDetectionTime parameters in the TimeAlertStrategyParameter
-(void) updateAlertParameter:(ATBeaconContent *) _beaconContent{
    TimeAlertStrategyParameter * strategyParameter = (TimeAlertStrategyParameter *) [_beaconContent beaconAlertParameter];
    double currentTime = CFAbsoluteTimeGetCurrent();
    //If we don't detect e beacon for more than 3s. we consider it's a new beacon detection
    //because the scanning period is done every 1.1s and a beacon is kept by iOs around 10s. in the beacon list when it does not detect it any more
    if([strategyParameter lastDetectionTime] + 3 < currentTime){
        strategyParameter.timeToShowAlert = currentTime + delayBeforeCreatingAlert;
    }
    strategyParameter.lastDetectionTime = currentTime;
}
  • Define the conditions when the beacon fits the strategy:
-(bool)isConditionValid:(ATBeaconAlertParameter *) beaconParameter {
    TimeAlertStrategyParameter * strategyParameter = (TimeAlertStrategyParameter *)beaconParameter;
    return [strategyParameter timeToShowAlert] < CFAbsoluteTimeGetCurrent();
}

Note:

The updateAlertParameter method is called by the BeaconAlertStrategy before the isConditionValid method, which means the BeaconAlertStrategyParameter transmited to the isConditionValid is up to date.

Step 5: Add the TimeAlertStrategy to the AdtagManager

In order to enable the SDK to apply a strategy to a beacon (assuming it has been properly configured in Adtag), you must register this strategy on the AdtagBeaconManager.

  • Open the ApplicationDelegate.m file
  • Register the AlertTimerStrategySecondWay on the AdtagBeaconManager, at the end of the didFinishLaunchingWithOptions method
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	[...]
  
    AlertTimerStrategySecondWay *alertTimeFilter = [[AlertTimerStrategySecondWay alloc]initWithMaxTime:60000 delayBeforeCreatingAlert:60000];
    [self addAlertStrategy:alertTimeFilter];
    return YES;
}
  • Last but not least, go to Adtag and populate a beacon's "Your Custom Strategy" field with this key to start testing.

Step 6: Start testing

  1. In Xcode, click on "Play" to launch the installation process of the application you just built on your phone

  2. Activate your beacon and put your device in its correct action range (as defined in Adtag)

  3. Wait for 60 seconds

  4. The title of the alert appears, as defined in Adtag.