-
Notifications
You must be signed in to change notification settings - Fork 4
Home
Obtaining API token information
The easiest way to get Ometria into your iOS project is by using CocoaPods.
-
If you are using CocoaPods for the first time, Install CocoaPods using
gem install cocoapods
in terminal. Otherwise, continue to Step 3. -
Run
pod setup
to create a local CocoaPods spec mirror. -
Create a Podfile in your Xcode project directory by running
pod init
in your terminal, edit the Podfile generated and add the following line:pod 'Ometria'
. -
Run
pod install
in your Xcode project directory. CocoaPods should download and install the library, and create a new Xcode workspace. Open up this workspace in Xcode or typingopen *.xcworkspace
in your terminal.
To benefit from the functionality provided by Ometria, you first have to initialize it. For this, you will be required to fill in the API Token that has been provided in your Ometria account.
The best place to do this is in application(_:didFinishLaunchingWithOptions:).
Initialize the library by first adding import Ometria
and then calling Ometria.initialize(apiToken:)
with your api token as its argument. Once you've called this method once, you can access your instance throughout the rest of your application with sharedInstance()
.
Ometria relies on Firebase Cloud Messaging in order to send push notifications to the mobile devices. This is done by adding ‘Firebase/Messaging’ as a dependency of Ometria. When installing the library via CocoaPods you will not have to worry about anything, as it will be automatically installed. If however you added Ometria manually in your project, you will have to install the Firebase SDK separately.
After initializing Ometria, make sure you do the same thing for Firebase Cloud Messaging as well. Once everything is done you will end up with something similar to this:
import Ometria
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Ometria.initialize(apiToken: "OMETRIA_API_TOKEN")
FirebaseApp.configure()
return
}
By default, Ometria logs any errors encountered during runtime. You can enable advanced logging if you want more information on what is happening in the background. In order to enable logging, you will be required to add the following line after initializing the library:
Ometria.sharedInstance().isLoggingEnabled = true
There are two main categories for differentiating events: automatically, and manually tracked. The two categories are not mutually exclusive, thus giving some events the possibility of being tracked automatically, as well as manually when necessary.
This is the list of events that Ometria SDK tracks automatically:
-
Application Installed - The app was just installed. Usually can't be sent when the app is actually installed, but instead only sent the first time the app is launched.
-
Application Launched - Someone has just launched the app.
-
Application Foregrounded - The app was already launched, but it was in the background. It has just been brought to the foreground.
-
Application Backgrounded - The app was in active use and has just been sent to the background.
-
Push Token Refreshed - The push token generated by Firebase has been updated.
-
Notification Received - A Push notification was received by the system.
-
Notification Interacted - The user has just clicked on / tapped on / opened a notification.
-
Error Occurred - An error occurred on the client side. We try to detect any problems with actual notification payload on our side, so we don't expect any errors which need to be fed back to end users.
Tracking events manually is straightforward with Ometria. After the SDK is initialized, you can track an event by calling its dedicated method like in the following example:
let myItem = OmetriaBasketItem(productId: "product-1",
sku: "sku-product-1",
quantity: 1,
price: 12.0)
let myItems = [myItem]
let myBasket = OmetriaBasket(totalPrice: 12.0, currency: "USD", items: myItems)
Ometria.sharedInstance().trackBasketUpdatedEvent(basket: myBasket)
You can choose to track any event from the following list, each requiring their own parameters:
-
Screen Viewed - This is already present as an automatically tracked event. However, if there are special scenarios where a screen is not presented as a ViewController, or you want to provide additional info related to the content that is being presented, you can manually track a 'Screen Viewed' event.
trackScreenViewedEvent(screenName: String, additionalInfo:[String: Codable])
-
Profile Identified - An app user has just identified itself as belonging to an Ometria profile. E.g. by supplying an e-mail address or logging in. Make sure to send as many of these tokens as you have available: it will often work with only e-mail, but having a customerId makes profile matching more robust.
-
trackProfileIdentifiedEvent(email: String)
-
trackProfileIdentifiedEvent(customerId: String)
-
-
Profile Deidentified - Undo a ‘Profile Identified' event. Use this if a user logs out, or otherwise signals that this device is no longer attached to the same person.
trackProfileDeidentifiedEvent()
-
Product Viewed - A visitor clicks/taps/views/highlights or otherwise shows interest in a product. Think for example searching for a term, and selecting one of the product previews from a set of results. Or browsing a category of clothes, and clicking on a specific shirt to see a larger picture. This event is about capturing interest from the visitor for this product. The product details must be sent to Ometria separately, using for example the server-to-server data API, or an e-commerce platform integration (like Shopify).
trackProductViewedEvent(productId: String)
-
Product Category Viewed - A visitor clicks/taps/views/highlights or otherwise shows interest in a product category. For example, a store sells clothing, and they tap on "Women's Footwear". The value is opaque, and is only used to create segments and automation campaigns in the Ometria app.
trackProductCategoryViewedEvent(category: String)
-
Product Added to Wishlist - The user has added this product to their wishlist.
trackWishlistAddedToEvent(productId: String)
-
Product Removed From Wishlist - The user has removed this product from their wishlist.
trackWishlistRemovedFromEvent(productId: String)
-
Basket Viewed - The user has viewed a dedicated page, screen or modal with the contents of the shopping basket
trackBasketViewedEvent()
-
Basket Updated - The user has changed their shopping basket.
trackBasketUpdatedEvent(basket: OmetriaBasket)
-
Order Completed - The order has been completed and paid for.
trackOrderCompletedEvent(orderId: String, basket: OmetriaBasket)
-
Deep Link Opened
trackDeepLinkOpenedEvent(link: String, screenName: String)
-
Custom Event - A custom event to trigger automation campaigns on actions that are not captured by the other available events.
trackCustomEvent(customEventType: String, additionalInfo: [String: Codable])
In order to reduce power and bandwidth consumption, the Ometria library doesn’t send the events one by one, unless you request it to do so. Instead, it composes batches of events that are sent periodically to the backend, during application runtime. You can request the library to send all remaining events to the backend whenever you want, by calling:
Ometria.sharedInstance().flush()
The library will automatically call this method every time the application is brought to foreground or sent to background.
You can completely clear all the events that have been tracked and not yet flushed. In order to do so you simply have to call the following method:
Ometria.sharedInstance().clear()
Ometria has the potential of providing personalized remote notifications for your mobile application, but in order to do so, it needs to be properly set up. To benefit from its full potential you need to cover the following steps:
-
Enable your app to receive push notifications by creating an appId and enabling the push notifications entitlement.
-
Setup a Firebase account and connect it to Ometria.
-
Enable Cloud Messaging on your Firebase account and provide your application’s SSL push certificate.
-
Configure push notifications in your application.
-
Add a Notification Service Extension to your app in order to enable receiving rich content notifications.
If you reached this section, we assume that you have already configured both the Ometria SDK, and Firebase. Once you managed to properly create or modify your application to support push notifications, you can move on to configure everything in your AppDelegate like so:
#import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Ometria.initialize(apiToken: "OMETRIA_API_TOKEN")
FirebaseApp.configure()
configurePushNotifications()
return true
}
func configurePushNotifications() {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) {
[weak self] (granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self?.getNotificationSettings()
}
UIApplication.shared.registerForRemoteNotifications()
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard #available(iOS 12.0, \*), settings.authorizationStatus == .provisional ||
settings.authorizationStatus == .authorized else {
return
}
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("Reaching Did register for remote notifications")
// handle your own device token handling here
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Reaching Did receive notification response")
// handle how your app reacts to receiving a push notification while it is running in foreground
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Reaching Will present notification")
// handle how you want your notification to be presented while the app is running in foreground
}
}
Ometria SDK will automatically source all the required tokens, and provide them to the backend. This way your app will start receiving notifications from Ometria, although handling those notifications while the app is running in foreground is up to you.
Starting with iOS 12.0, Apple enabled regular applications to receive and display notifications that contain media content such as images. Ometria uses these feature to further enhance your application, but it requires you to add a new target extension that intercepts all push notifications containing 'mutable-content: 1'
in the payload.
To do so you simply have to go to File → New → Target, and select Notification Service Extension and select Next.
You will then be able to see a new item in your target list.
You will then need to make sure that the Ometria SDK is also available to this new target. To accomplish this you will have to update your podfile to include your newly added target and specify Ometria as a dependency just like you did with the app.
If you try to run pod install
and then build the extension, you will get some compilation errors. Since we are trying to run Ometria on an extension, there are several methods in the SDK that are not supported, although not being used. In order to silence those errors and get everything functional you will have to update your podfile ending up with something like this:
platform :ios, '10.0'
target 'OmetriaSample' do
use_frameworks!
pod 'Ometria', :path => '../../SDK'
target 'OmetriaSampleNotificationService' do
pod 'Ometria', :path => '../../SDK'
end
end
post_install do |installer|
installer.pods_project.targets.each do |target|
if target.name == 'Ometria'
target.build_configurations.each do |config|
config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'No'
end
end
end
end
Once you have done this, you will once again be able to run your application and the extension you have just created.
To finalize the implementation and allow Ometria to intercept notifications, open the NotificationService
class and replace the content with the following:
import UserNotifications
import Ometria
class NotificationService: OmetriaNotificationServiceExtension {
}
Now you are able to receive notifications from Ometria and you are also be able to see the images that are attached to your notifications.