Log OneSignal Push Notification with Firebase Analytics Event - ios

So my goal is to log event any push notification that comes up on my app. I'm using Firebase Analytics to log any event and I already know how to use it using :
Analytics.logEvent(FirebaseEventName, parameters: [:])
But is it possible to log event a push notification? I'm using OneSignal as my Push Notification service.

I've found my answer. But my method required Backend to be involved. Which I don't have the answer because I don't handle the Backend part. The following answer is only just for iOS part only.
So, the method is using OneSignal method, and it's implemented in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
If you're already using OneSignal for iOS you should already write below code in didFinishLaunchingWithOptions
OneSignal.initWithLaunchOptions(launchOptions, appId: ONE_SIGNAL_APPID, handleNotificationReceived: { (notification) in
let additionalData = notification?.payload.additionalData // Get additional data such as custom flaging from backend
if additionalData != nil { // A condition to avoid crash if additionalData is empty
let customFlag:String = additionalData!["tipe"] as! String // Get value of the custom flag, in this case mine is "tipe", and store the value to customFlag
Analytics.logEvent(customFlag, parameters: [:]) // Send Log Event to Firebase
}
}, handleNotificationAction: { (result) in
}, settings: [kOSSettingsKeyInFocusDisplayOption: OSNotificationDisplayType.none.rawValue,kOSSettingsKeyAutoPrompt : true])
For example, if you print additionalData the value should be looking like
[AnyHashable("tipe"): inbox]
And this value is set/declared in Backend part.

Related

How do I prevent Alert when App is on Foreground with Incoming OneSignal Push Notification?

When my app is in the foreground, there is a alert that appears. How do I prevent this from appearing when receiving push notifications?
In your didFinishLaunchingWithOptions method of AppDelegate you have to add kOSSettingsKeyInAppAlerts = NO
[OneSignal initWithLaunchOptions:launchOptions appId:ONESIGNAL_APPID handleNotificationReceived:nil handleNotificationAction:nil
settings:#{kOSSettingsKeyInAppAlerts:#NO}];
For Swift 3.0
// Initialize OngeSignal with Settings for Push Notifications
OneSignal.initWithLaunchOptions(launchOptions, appId: Constants.OneSignalAppID, handleNotificationReceived: nil, handleNotificationAction: {
(result) in
// Do Something with Notification Result
}, settings: [kOSSettingsKeyInFocusDisplayOption : OSNotificationDisplayType.none.rawValue])
By default OneSignal shows notifications as alert dialogs when the app is infocus. To change this pass kOSSettingsKeyInFocusDisplayOption with the value OSNotificationDisplayTypeNotification or OSNotificationDisplayTypeNone to settings on initWithLaunchOptions.
I achieved it this way. Add the following code in your AppDelegate didFinishLaunchingWithOptions
OneSignal.inFocusDisplayType = OSNotificationDisplayType.none
on last line in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
OneSignal.inFocusDisplayType = OSNotificationDisplayType.none
return true }
we have these 3 options
public enum OSNotificationDisplayType : UInt {
/*Notification is silent, or app is in focus but InAppAlertNotifications are disabled*/
case none
/*Default UIAlertView display*/
case inAppAlert
/*iOS native notification display*/
case notification
}
Here's OneSignal Documentation

Send push notification to a specific test device using OneSignal push notification service

I added push notification support to my iOS app using OneSignal some time before. The app is made in Xcode with Swift.
I want to send a test push notification only to my test device(s). I the documentation I found the following manual: How do I send a notification to a single user?
I managed to create the segment but I don't know where to put this peace of code: OneSignal.sendTag("is_test", "true")
Does anybody know where I have to put this piece of code to make it working as I described above?
I uploaded my code here: https://codeshare.io/DxcNn
Thanks,
David.
Update:
OneSignal now also supports to set a device as test device without doing something in the code. You can also download your own app from App Store and use it as test device. Just select you device from devices list one OneSignal and mark it as test device. You can find your device in the list by model, version and/or time added.
The sendTag method is from the device sdk. In your case iOS.
https://documentation.onesignal.com/docs/ios-native-sdk#section--sendtag-
You should do this anytime after initWithLaunchOptions in the app delegate. Updated code based on comments
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let oneSignal = OneSignal(launchOptions: launchOptions, appId: "here_is_my_onesignal_app_id") { (message, additionalData, isActive) in
NSLog("OneSignal Notification opened:\nMessage: %#", message)
if additionalData != nil {
NSLog("additionalData: %#", additionalData)
// Check for and read any custom values you added to the notification
// This done with the "Additonal Data" section the dashbaord.
// OR setting the 'data' field on our REST API.
if let customKey = additionalData["customKey"] as! String? {
NSLog("customKey: %#", customKey)
}
}
}
OneSignal.defaultClient().sendTag("is_test", value: "true")
// Override point for customization after application launch.
return true
}

How do you get the push object sent to iOS device from Urban Airship (Objective-c)?

I am receiving push notifications from Urban Airship with custom information. It shows up on the log but I am attempting to get the object so I can parse the data to store specific value, such as 1 of "quest_id". How can I go about retrieving the object or where can I look into? Any suggestions or insight would be greatly appreciated.
Depending on the push notification configuration you've made in Info.plist, you should implement the following methods in AppDelegate.swift:
func application(application:didReceiveRemoteNotification:)
or
application(application:didReceiveRemoteNotification:fetchCompletionHandler:)
Here is a basic example of how you can do it:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if let questID = userInfo["quest_id"] as? Int {
print(questID) // prints 1
}
if let question = userInfo["question"] as? String {
print(question) // prints "What is threading?"
}
completionHandler(UIBackgroundFetchResult.NoData)
}
you would have to implement (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo method defined in UIApplicationDelegate.This method will be called when a push notification is received.You can then use the userInfo dictionary it will contain all the push information
Either use the mentioned app delegate methods or since you are using Urban Airship you can set a UAPushNotificationDelegate on the UAPush instance.

How to get notification additionaldata(payloadData) that was at AppDelegate' didFinishLunchingWithOptions if the user didn't open the notification

I am currently using OneSignal for notification service to my app.I really need a help with accessing notification additionaldata(payload data) from AppDelegate inside didFinishLunchingWithOption where OneSignal API can give me like this.
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var data : [NSObject : AnyObject]!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let oneSignal = OneSignal(launchOptions: launchOptions, appId: "48755d3d-abc0-4bac-8f71-095729bb3a65") { (message, additionalData, isActive) in
NSLog("OneSignal Notification opened:\nMessage: %#", message)
if additionalData != nil {
NSLog("additionalData: %#", additionalData)
self.data = additionalData
print(self.data)
}
}
oneSignal.enableInAppAlertNotification(true)
return true
}
}
but,I can only get the data if user click notification when appear or open it from notification center.So,if user neglect that notification without tapping when appear or without swiping or tapping from notification center,how do i get the additional data?
Actually,I want to store all payload data every time it comes into my device at realm database and fetch the data from my server according to that payload data.
You should use application(_:didReceiveRemoteNotification:fetchCompletionHandler:).
If you have enabled remote notifications background mode most of your notifications will be delivered even if the app is not running in the foreground. The only caveat being that the app must have been launched (since notifications are being pushed the user has done this) and it mustn't have been force-quit by the user.
More info in Apple's docs about that specific method.
Or in the "Local and Remote Notification Programming Guide's" notification handling chapter
You can extract all the payload in did finishLaunching by following method..
Let data = launchOptions.objectForKey(UIApplicationLaunchOptionsUIApplicationLaunchOptionsRemoteNotificationUIApplicationLaunchOptionsUIApplicationLaunchOptionsRemoteNotificationKey)

Handling push notifications payload data

I am searching the way about how to handle push notification payload data as soon as the notification reaches to the client app without opening or tapping it.And I am still not getting the data unless the user tap or open it from notification center or banner or alert.The function didReceiveRemoteNotification only triggered when the user click the notification on the screen.So,how to get the notification payload data when the notification arrive to client app even the user ignore(without open or tap) it.
INFO : I heard that GCM(Google Cloud Messaging) can make notification handler if the client app user tapped the notification or not.It can catch the notification payload json data as soon as it reach the client app without even need user to tap or open it.Is that right?
I really need a hand to pick me up with getting notification payload data on ios without even need a user to open or tap it.
Update : The app is still running on device which mean it was active.I can get the payload data when i click my notification which was "{aps:} json i get it.But,I still cant get the data when i don't open the notification"
Here is my state
When the app was at foreground,I get the data.
1.I run the App,
2.Send Notification,
3.Get the notification with an alert,
4.I get the data(payload).
Work fine when app is active.
But,when the app reach to background
1.Run The app,
2.Close The App by pressing home button,
3.Send Notification,
4.Get the notification.
5.But,cant get the data until i click notification that I was receive at banner
or notification center.
But,when i click the notification at banner or notification it went to app and then i get the data.
Is there anyway that i can get the data if the app in background when the notification received.
Here is the code :
import UIKit
import RealmSwift
let realm = try! Realm()
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var data : [NSObject : AnyObject]!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//one singnal is the push notification service that i use for push notification.
let oneSignal = OneSignal(launchOptions: launchOptions, appId: "__app_id__") { (message, additionalData, isActive) in
NSLog("OneSignal Notification opened:\nMessage: %#", message)
if additionalData != nil {
NSLog("additionalData: %#", additionalData)
}
}
oneSignal.enableInAppAlertNotification(true)
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
print("User Info : \(userInfo)")
if let custom = userInfo["custom"] as? NSDictionary{
if let a = custom["a"] as? NSDictionary{
print("A : \(a)")
}
}
}
I came across the same problem. As mentioned in the previous comments, this post is quite helpful.
According to Apple,
When a remote notification arrives, the system displays the
notification to the user and launches the app in the background (if
needed) so that it can call this method. Launching your app in the
background gives you time to process the notification and download any
data associated with it, minimizing the amount of time that elapses
between the arrival of the notification and displaying that data to
the user.
The first thing you have to do is to allow your app to do something when in background. You do this by adding Required background mode in your info.plist, then add it App downloads content in response to push notifications. Your info.plist should look something like this:
Now this is done, your app should awake when it receive a notification. You can execute a small code inside didReceiveRemoteNotification. Such as this.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
//do some code here
UIBackgroundFetchResult.NewData
}
Note that you have to pay attention to the completionHandler:
As soon as you finish processing the notification, you must call the
block in the handler parameter or your app will be terminated. Your
app has up to 30 seconds of wall-clock time to process the
notification and call the specified completion handler block.
Let me know if everything is clear :)

Resources