iOS Question Send Firebase Notification to Token Help Please???

Mashiane

Expert
Licensed User
Longtime User
Hi there

Whilst the code to send to a particular topic works well, there seems to be no example for IOS to send to a particular token. Can someone please advise how can I please make that work?

NB: The code below works for topic based notifications

In my Main, I have the following methods

B4X:
Private Sub Application_PushToken (Success As Boolean, Token() As Byte)
    FirebaseToken = bc.HexFromBytes(Token)
   Log("pushtoken: " & FirebaseToken)
End Sub

Private Sub fm_FCMConnected
   Log("FCMConnected")
   'here we can subscribe and unsubscribe from topics
   fm.SubscribeToTopic("ios_general") 'add ios_ prefix to all topics
   'modTGIF.FirebaseToken = GetToken
   Log("connected token: " & GetToken)
End Sub

Private Sub GetToken As String
   Dim no As NativeObject
   Dim token As NativeObject = no.Initialize("FIRInstanceID").RunMethod("instanceID", Null).RunMethod("token", Null)
   If token.IsInitialized Then Return token.AsString Else Return ""
End Sub


Private Sub Application_RemoteNotification (Message As Map, CompletionHandler As CompletionHandler)
   Dim msg As Map = Message
   Log($"Message arrived: ${Message}"$)
   'get the data from the notification
   Dim notifid As String = modMashiane.StateManager.GetSetting("notification")
   If notifid = "" Then notifid = "1"
   Dim from_id As String = msg.GetDefault("from_id","")
   Dim from_token As String = msg.GetDefault("from_token","")
   Dim to_id As String = msg.GetDefault("to_id","")
   Dim to_token As String = msg.GetDefault("to_token","")
   Dim body As String = msg.GetDefault("body","")
   Dim title As String = msg.GetDefault("title","")
   Dim notif_type As String = msg.GetDefault("notif_type","")
   Dim todayJSON As String = msg.GetDefault("currentpage","")
               
   If from_id.Length > 0 And from_token.Length > 0 Then
      'save the tokens for later retrieval
      modMashiane.StateManager.SetSetting("firebase_" & from_id, from_token)
    Log("From Firebase Token Saved.")
   End If
   If to_id.Length > 0 And to_token.Length > 0 Then
      'save the tokens for later retrieval
      modMashiane.StateManager.SetSetting("firebase_" & to_id, to_token)
    Log("To Firebase Token Saved.")
   End If
 
   ' only show a notification if its not coming from me
   'If from_id <> modTGIF.auser_id Then
      Dim n As Notification
      n.Initialize(DateTime.Now)
    n.PlaySound = True
      Select Case notif_type
    Case modMashiane.NotifEnum.request
        n.AlertBody = body
        'n.SetInfo(title, body, frmNotifications)
      Case modMashiane.NotifEnum.following 
        n.AlertBody = body
        modMashiane.StateManager.setSetting("otheruser", from_id) 
        'n.SetInfo(title, body, frmProfileOther)
    Case modMashiane.NotifEnum.like
        n.AlertBody = body
        modMashiane.StateManager.SetSetting("currentpage", todayJSON)
        'n.SetInfo(title, body, frmLikes)
    Case modMashiane.NotifEnum.comment
        n.AlertBody = body
        modMashiane.StateManager.SetSetting("currentpage", todayJSON)
        'n.SetInfo(title, body, frmComments)
    Case Else
        n.AlertBody = body
        'n.SetInfo(title, body, Null)
      End Select
    n.Register
    'App.ApplicationIconBadgeNumber = 1
    'Dim id As Int = notifid
    'n.Notify(id)
    'id = id + 1
    'modMashiane.StateManager.SetSetting("notification",id)
   CompletionHandler.Complete
End Sub

Private Sub Application_Active
   fm.FCMConnect 'should be called from Application_Active
End Sub

Private Sub Application_Background
   fm.FCMDisconnect 'should be called from Application_Background
End Sub

In Process_Globals I have..

B4X:
Public analytics As FirebaseAnalytics
    Public fm As FirebaseMessaging
Private bc As ByteConverter

and in my Application_Start

B4X:
analytics.Initialize
    App.RegisterUserNotifications(True, True, True)
    App.RegisterForRemoteNotifications
    fm.Initialize("fm")

And the edited topic based firebase method is...

B4X:
public Sub FireBaseSendNotification2Topic(frm As Object, JobName As String, Topic As String, Title As String, notifMap As Map)
    'read from the saved map
    Dim from_id As String = notifMap.get("from_id")
    Dim from_name As String = notifMap.get("from_name")
    Dim from_token As String = notifMap.get("from_token")
    Dim notif_type As String = notifMap.get("notif_type")
    Dim about As String = notifMap.GetDefault("about","")
    Dim id As String = notifMap.GetDefault("id","")
    Dim Body As String
    Select Case notif_type
    Case "project"
        Body = about & ": New Donation Project"
    Case "event"
        Body = about & ": New Event"
    Case "announcement"
        Body = about & ": New Announcement"
    Case "registered"
        Body = from_name & ": Registered"
    Case "online"
        Body = from_name & " is online now."
    Case "tookpicture"
        Body = from_name & " has taken a picture."
    Case "uploadpicture"
        Body = from_name & " has uploaded a picture."
    Case "reveal"
        Body = from_name & " has revealed his picture(s)."
    End Select
    Dim data As Map
    data.Initialize
    data.Put("title", Title)
    data.Put("icon", "new")
    data.Put("delay_while_idle", True)
    data.Put("from_id", from_id)
    data.put("from_name", from_name)
    data.Put("from_token", from_token)
    data.put("dry_run", False)
    data.Put("body", Body)
    data.Put("id", id)
    data.Put("notif_type", notif_type)
 
    ' define the notification 
   Dim Job As HttpJob
   Job.Initialize("firebase", frm)
   Job.Tag = "firebasenotification"
   Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
   m.Put("data", data)
   If Topic.StartsWith("ios_") Then
    Dim iosalert As Map =  CreateMap("title": Title, "body": Body, "sound": "default")
    m.Put("notification", iosalert)
    m.Put("priority", 10)
   End If
   Dim jg As JSONGenerator
    jg.Initialize(m)
    Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
    Job.GetRequest.SetContentType("application/json;charset=UTF-8")
    Job.GetRequest.SetHeader("Authorization", "key=" & modTGIF.FireBaseApiKey)
End Sub

1. From one of the forum posts, the GetToken method "sometimes" returns a token and "sometimes" it does not.
2. Does fm.FCMConnect create a new token, if so where can that be trapped and used
3. The Application_PushToken is different from GetToken, thus which one should I use?

Part of the b4a code to send to a token was defined as

B4X:
Dim m As Map = CreateMap("to": $"${id}"$)

where the id is the token, does b4i use a similar approach?

I also saw an example using this methid

B4X:
'Private Sub CheckForPushMessage
'   If App.LaunchOptions.IsInitialized And App.LaunchOptions.ContainsKey("UIApplicationLaunchOptionsRemoteNotificationKey") Then
'     Dim data As Object = App.LaunchOptions.Get("UIApplicationLaunchOptionsRemoteNotificationKey")
'     Dim no As NativeObject = App
'     no.GetField("delegate").RunMethod("application:didReceiveRemoteNotification:", Array(App, data))
'   End If
'End Sub

I presume this is not relevant for Firebase??

As I'm new to this, perhaps there are things I might have confused, there are numerous posts to this topic, so please bear with me and help out if you can.

Ta!
 
Top