Skip to content

Objective C Guide

Kieran Graham edited this page Nov 23, 2016 · 46 revisions

Permissions

Required Background Modes

You need to add the Location Updates background mode to your app's capabilities; you can either use Xcode's UI or edit the Info.plist file.

In Xcode

Enable Location Updates Background Mode in Xcode

Modify Info.plist

<key>UIBackgroundModes</key>
<array>
  <string>location</string>
</array>

iOS >8.0

For iOS 8.0 or later, you need to add NSLocationAlwaysUsageDescription key to your Info.plist file. This key should contain a text string, this text will be displayed when iOS displays Locations services permission's alert in your app.

<key>NSLocationAlwaysUsageDescription</key>
<string>Data stays secure on your phone. GPS will help us to detect arrivals and departures. Data will be posted anonymously.</string>

### iOS >10.0

For iOS 10.0 or later, you need to add NSMotionUsageDescription key to your Info.plist file. This key should contain a text string, this text will be displayed when iOS displays device’s Motion & Fitness permission's alert in your app.

<key>NSMotionUsageDescription</key>
<string>Data stays secure on your phone. Motion activity will help us to detect arrivals and departures. Data will be posted anonymously.</string>

Setting up the SDK

Import Headers

Using CocoaPods

To import predict.io in your Objective-C project using CocoaPods:

#import <PredictIO-iOS/PredictIO.h>
Not Using CocoaPods

To import predict.io in Objective-C project if not using CocoaPods:

#import "PredictIO.h"

Overview

  • Instantiate predict.io - Instantiate predict.io and setup the delegate.
  • Start predict.io - Start getting callbacks from predict.io.
  • Stop predict.io - Stop getting callbacks from predict.io.
  • Kick start GPS - Manually activate GPS for a short period of time.
  • Get predict.io status - Check status of predict.io, whether it is active or not.
  • Get the device identifier - An alphanumeric string that uniquely identifies a device to predict.io.
  • Set Custom Parameters - Set custom parameters which can then be sent to a user defined webhook URL.
  • Set Webhook URL - Set a webhook URL where all the detected events can then be forwarded along with the custom parameters. This webhook will not support additional authentication. So any additional validation of legitimate requests must take place.
  • Home and work zones - Get home and work zones detected by predict.io
  • Clear zones history - Clear historic zone data which is used to predict different zones like home or work zones

Details

Instantiate predict.io

Here we instantiate predict.io, set the API key and its delegate.

// Implement PredictIODelegate in your AppDelegate and instantiate predict.io Object

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

...
    // The following code sample instantiate predict.io SDK and sets the delegate method:
    PredictIO *predictIO = [PredictIO sharedInstance];
    predictIO.delegate = self;
    predictIO.apiKey = @"YOUR-API-KEY";
...
}
Start predict.io

This starts predict.io if the delegate and the API-Key are set, otherwise it returns an Error.

/*
 * This starts predict.io if the delegate and the API-Key are set, otherwise it returns an Error
 * @param handler: The argument to the completion handler block is an error object that contains
 * the description of the error. If predict.io is started successfully, then error object is nil
 */

- (void)startWithCompletionHandler:(void(^)(NSError *error))handler;
Sample code
[[PredictIO sharedInstance] startWithCompletionHandler:^(NSError *error) {
    if (error) {
        NSLog(@"Error : %@", [error description]);
    }
}];
Stop predict.io
- (void)stop;
Sample code
[[PredictIO sharedInstance] stop];
Kick Start GPS

Manually activate the GPS for a short period of time.

/*
 * Manually activate the GPS for a short period of time i.e. 90 seconds
 * predict.io manages the GPS for an optimal battery performance
 * if you need a more precise location updates in didUpdateLocations: method
 * use this method to make sure that the GPS is active.
 */
- (void)kickStartGPS;
Sample code
[[PredictIO sharedInstance] kickStartGPS];
predict.io Status

This method returns the status of predict.io, PredictIOStatus (i.e. if it is active or not).

/*
 * This method returns predict.io's status, PredictIOStatus (i.e. if it is active or not).
 * Discussion: PredictIOStatus represents the current predict.io state.
 * PredictIOStatusActive: predict.io is in a working, active state.
 * PredictIOStatusLocationServicesDisabled: predict.io is not in a working state as the location services are disabled.
 * PredictIOStatusInsufficientPermission: predict.io is not in a working state as the permissions to use location services are not provided by the user.
 * PredictIOStatusInActive: predict.io has not been started. It is in an inactive state.
 */
- (PredictIOStatus)status;
Sample code
PredictIOStatus status = [[PredictIO sharedInstance] status];
Device Identifier

An alphanumeric string that uniquely identifies a device to predict.io.

/*
 * An alphanumeric string that uniquely identifies a device to the predict.io
 */
- (NSString *)deviceIdentifier;
Sample code
NSString *deviceIdentifier = [[PredictIO sharedInstance] deviceIdentifier];
Custom Parameters

Set custom parameters which can be sent to an app defined webhook URL.

/*
 * Set custom parameters which can be sent to an app defined webhook URL
 * @param key: Key to identify a custom parameter value
 * @param value: Custom parameter value
 */
- (void)setCustomParameter:(NSString *)key andValue:(NSString *)value;
Sample Code
[[PredictIO sharedInstance] setCustomParameter:@"device_token" andValue:@"ABC123"];
Webhook URL

Set a webhook URL where all detected events are forwarded to, along with the custom parameters. Please note that this webhook does not support any additional authentication. So any additional validation of legitimate requests must take place at developer end.

/*
 * Set a webhook URL where all detected events are forwarded to, along with the custom parameters.
 * This webhook does not support additional authentication. So any additional validation of legitimate requests must take place.
 * @param url: The webhook URL
 */
- (void)setWebhookURL:(NSString *)url;
Sample Code
[[PredictIO sharedInstance] setWebhookURL:@"https://www.example.com/send_notification"];
Home and Work Zones

Use the following properties to get the home and work zones.

/* Home zone of the user detected by PredicIO */
@property (nonatomic, strong) PIOZone *homeZone;

/* Work zone of the user detected by PredicIO */
@property (nonatomic, strong) PIOZone *workZone;
Clear Zone History

Clear historic zone data which is used to predict different zones like home or work zones.

/*
 * Clear historic zone data used to predict different zones like home or work zones
 */
- (void)clearZoneHistory;
Sample Code
[[PredictIO sharedInstance] clearZoneHistory];

PIOTripSegment

PIOTripSegment represents a trip segment that contains departure location, departure time, arrival location, arrival time and transportation mode for this segment.

@interface PIOTripSegment : NSObject

/** Unique ID for a trip segment, e.g. to link departure and arrival events */
@property (strong, readonly) NSString *UUID;
/** Location from where the user departed */
@property (strong, readonly) CLLocation *departureLocation;
/** Location where the user arrived and ended the trip */
@property (strong, readonly) CLLocation *arrivalLocation;
/** Time of departure */
@property (strong, readonly) NSDate *departureTime;
/** Time of arrival */
@property (strong, readonly) NSDate *arrivalTime;
/** Predicted mode of transportation */
@property (nonatomic, readonly) TransportationMode transportationMode;
/** Departure Zone */
@property (strong, readonly) PIOZone *departureZone;
/** Arrival Zone */
@property (strong, readonly) PIOZone *arrivalZone;

@end

Transportation Mode

Transportation mode represents mode of transportation that is predicted by predict.io during the trip

typedef NS_ENUM(int, TransportationMode) {
    // current transportation mode is Undetermined
    TransportationModeUndetermined = 0,

    // current transportation mode is Car
    TransportationModeCar,

    // current transportation mode is other than Car
    TransportationModeNonCar
};

Home & Work Zones

predict.io predicts user home and work zones after some days/trips of tracker activation.

PIOZone
typedef NS_ENUM(int, PIOZoneType) {
    PIOZoneTypeOther = 0,
    PIOZoneTypeHome,
    PIOZoneTypeWork
};

@interface PIOZone : NSObject

@property (assign, readonly) PIOZoneType zoneType;
@property (assign, readonly) CLLocationDistance radius;
@property (assign, readonly) CLLocationCoordinate2D center;
...
@end

PIOZone is a data object that contains information about particular zone.

  • Center: The center point (latitude, longitude) of zone.
  • Radius: The radius of a zone which at the moment is always 100m.
  • ZoneType: Zone type could be PIOZoneTypeOther, PIOZoneTypeHome, PIOZoneTypeWork.

Zone Information in PIOTripSegment:

Departed and arrived event zone information is present in PIOTripSegment object returned in particular event callback. A user is considered to be in a particular zone if event location lies within the radius of that zone.

SDK Functions

Overview

Event Callbacks Flow Diagram

PredictIOEventsFlow

####Details

Departing

This method is invoked when predict.io detects that the user is about to depart

/* This method is invoked when predict.io detects that the user is about to depart
 * from his location and is approaching to his vehicle
 * @param tripSegment: PIOTripSegment contains details about departing event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureZone: Departure zone
 */
- (void)departing:(PIOTripSegment *)tripSegment;
Departed

This method is invoked when predict.io detects that the user has just departed

/* This method is invoked when predict.io detects that the user has just departed
 * from his location and have started a new trip
 * @param tripSegment: PIOTripSegment contains details about departure event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureTime: Time of departure
 *  departureZone: Departure zone
 */
- (void)departed:(PIOTripSegment *)tripSegment;
Canceled Departure

This method is invoked when predict.io is unable to validate the last departure event.

/* This method is invoked when predict.io is unable to validate the last departure event.
 * This can be due to invalid data received from sensors or the trip amplitude, i.e. If the
 * trip takes less than 2 minutes (120 seconds) or the distance travelled is less than 1km
 * @param tripSegment: PIOTripSegment contains details about canceled departure event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureTime: Time of departure
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 */
- (void)canceledDeparture:(PIOTripSegment *)tripSegment;
Departure Canceled [Deprecated from 3.2.0]

This method is invoked when predict.io is unable to validate the last departure event.

/* This method is invoked when predict.io is unable to validate the last departure event.
 * This can be due to invalid data received from sensors or the trip amplitude, i.e. If the
 * trip takes less than 2 minutes (120 seconds) or the distance travelled is less than 1km
 * @param tripSegment: PIOTripSegment contains details about departure canceled event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureTime: Time of departure
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 */
- (void)departureCanceled:(PIOTripSegment *)tripSegment;
Detected Transportation Mode

This method is invoked when predict.io detects a transportation mode

/* This method is invoked when predict.io detects a transportation mode
 * @param tripSegment: PIOTripSegment contains details about user's transportation mode
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureTime: Time of departure
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 */
- (void)detectedTransportationMode:(PIOTripSegment *)tripSegment;
Transportation Mode [Deprecated from 3.2.0]

This method is invoked when predict.io detects a transportation mode

/* This method is invoked when predict.io detects a transportation mode
 * @param tripSegment: PIOTripSegment contains details about user's transportation mode
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  departureTime: Time of departure
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 */
- (void)transportationMode:(PIOTripSegment *)tripSegment;
Suspected Arrival

This method is invoked when predict.io suspects that the user has just arrived

/* This method is invoked when predict.io suspects that the user has just arrived
 * at his location and have ended a trip
 * Most of the time it is followed by a confirmed arrived event
 * If you need only confirmed arrival events, use arrived method (below) instead
 * @param tripSegment: PIOTripSegment contains details about suspected arrival event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  arrivalLocation: The Location where the user arrived and ended the trip
 *  departureTime: Time of departure
 *  arrivalTime: Time of arrival
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 *  arrivalZone: Arrival Zone
 */
- (void)suspectedArrival:(PIOTripSegment *)tripSegment;
Arrival Suspected [Deprecated from 3.2.0]

This method is invoked when predict.io suspects that the user has just arrived

/* This method is invoked when predict.io suspects that the user has just arrived
 * at his location and have ended a trip
 * Most of the time it is followed by a confirmed arrived event
 * If you need only confirmed arrival events, use arrived method (below) instead
 * @param tripSegment: PIOTripSegment contains details about arrival suspected event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  arrivalLocation: The Location where the user arrived and ended the trip
 *  departureTime: Time of departure
 *  arrivalTime: Time of arrival
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 *  arrivalZone: Arrival Zone
 */
- (void)arrivalSuspected:(PIOTripSegment *)tripSegment;
Arrived

This method is invoked when predict.io detects that the user has just arrived at destination.

/* This method is invoked when predict.io detects that the user has just arrived at destination
 * @param tripSegment: PIOTripSegment contains details about arrival event
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  arrivalLocation: The Location where the user arrived and ended the trip
 *  departureTime: Time of departure
 *  arrivalTime: Time of arrival
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 *  arrivalZone: Arrival Zone
 */
- (void)arrived:(PIOTripSegment *)tripSegment;
Searching In Perimeter

This method is invoked when predict.io detects that the user is searching for a parking space at a specific location in his/her car.

/* This method is invoked when predict.io detects that the user is searching for a
 * parking space around a specific location
 * @param location: Location where predict.io identifies that user is searching for
 * a parking space
 */
- (void)searchingInPerimeter:(CLLocation *)searchingLocation;
Stationary After Arrival

This method is invoked after few minutes of arriving at the destination and detects if the user is stationary or not.

/* This method is invoked after few minutes of arriving at the destination and detects if the user is stationary or not
 * @param tripSegment: PIOTripSegment contains details about stationary after arrival
 * @discussion: The following properties are populated currently:
 *  UUID: Unique ID for a trip segment, e.g. to link departure and arrival events
 *  departureLocation: The Location from where the user departed
 *  arrivalLocation: The Location where the user arrived and ended the trip
 *  departureTime: Time of departure
 *  arrivalTime: Time of arrival
 *  transportationMode: Mode of transportation
 *  departureZone: Departure zone
 *  arrivalZone: Arrival Zone
 *  stationary: User activity status as stationary or not
 */
- (void)beingStationaryAfterArrival:(PIOTripSegment *)tripSegment;
Traveled By Airplane

This method is invoked when predict.io detects that the user has traveled by airplane.

/* This method is invoked when predict.io detects that the user has traveled by airplane and
 * just arrived at destination, this event is independent of usual vehicle trip detection and
 * will not have predecessor departed event
 * @param tripSegment: PIOTripSegment contains details about traveled by airplane event
 * @discussion: The following properties are populated currently
 *  UUID: Unique ID for a trip segment
 *  departureLocation: The Location from where the user started journey
 *  arrivalLocation: The Location where the user arrived and ended the journey
 *  departureTime: time of departure
 *  arrivalTime: time of arrival
 */
- (void)traveledByAirplane:(PIOTripSegment *)tripSegment;
Did Update Location

This method is invoked when new location information is received from location services

/* This is invoked when new location information is received from location services
 * Implemented this method if you need raw GPS data, instead of creating a new location manager
 * as, it is not recommended to use multiple location managers in a single app
 * @param location: New location
 */
- (void)didUpdateLocation:(CLLocation *)location;

Notifications

/* These notifications are sent out after the equivalent delegate message is called.
 * The params of delegate message are sent as a dictionary and can be fetched from
 * the userInfo property of NSNotification.
 */
FOUNDATION_EXPORT NSString *const PIODepartingNotification;
FOUNDATION_EXPORT NSString *const PIODepartedNotification;
FOUNDATION_EXPORT NSString *const PIOCanceledDepartureNotification;
FOUNDATION_EXPORT NSString *const PIODepartureCanceledNotification            //deprecated from 3.2.0
DEPRECATED_MSG_ATTRIBUTE("Use PIOCanceledDepartureNotification");
FOUNDATION_EXPORT NSString *const PIOSuspectedArrivalNotification;
FOUNDATION_EXPORT NSString *const PIOArrivalSuspectedNotification             //deprecated from 3.2.0
DEPRECATED_MSG_ATTRIBUTE("Use PIOSuspectedArrivalNotification");
FOUNDATION_EXPORT NSString *const PIOArrivedNotification;
FOUNDATION_EXPORT NSString *const PIOSearchingParkingNotification;
FOUNDATION_EXPORT NSString *const PIODetectedTransportationModeNotification;
FOUNDATION_EXPORT NSString *const PIOTransportationModeNotification           //deprecated from 3.2.0
DEPRECATED_MSG_ATTRIBUTE("Use PIODetectedTransportationModeNotification");
FOUNDATION_EXPORT NSString *const PIOBeingStationaryAfterArrivalNotification;
FOUNDATION_EXPORT NSString *const PIOTraveledByAirplaneNotification;

Remote Notifications Using predict.io

predict.io's SDK also provides a mechanism which can be used to send remote notifications to the user's devices when a departure or arrival event is detected. To trigger these notifications the SDK provides the following two methods,

- (void)setCustomParameter:(NSString )key andValue:(NSString )value;
- (void)setWebhookURL:(NSString *)url;

To send a remote notification to an iOS device, the device token of the device is needed. Once the device token is fetched by using the appropriate iOS API, it needs to be sent to predict.io's servers. To do this, use the setCustomParameter method. The key should be 'device_token' and the value should be the actual device token.

[[PredictIO sharedInstance] setCustomParameter:@"device_token" andValue:@"ABC123"];

In order to deliver successfully a remote notification, please notice that the server will actually originate the remote notification. In technical terms, this server is called the provider. Whenever a departure or arrival event is detected, predict.io's SDK can communicate with the provider using a HTTP callback which should be implemented by the provider. The provider HTTP callback URL can be set using the method setWebhookURL.

[[PredictIO sharedInstance] setWebhookURL:@"https://api.example.com/send_notification"];

As soon as the departure or arrival event is detected, the predict.io SDK sends the appropriate event to the webhook URL along with the device token. The provider at the webhook URL will send a remote notification to that specific device based on the event detected.