问题
I'm developing an app and am trying to work out how I can notify a specific user when a different user performs a specific action. I'm trying to avoid setting up my own backend server, as I believe that what I want to do can be accomplished by OneSignal/Firebase.
I haven't tried it yet, but I figure with each user I could get their own OneSignal player_id (which is basically the OneSignal device_id), upload that to my firebase database, then when I want to send a push notification I simply pull the user's player_id from firebase and then use it to create a notification with OneSignals send to specific device, where using player_ids does not require the API Auth Key.
Though after looking through the documentation I'm not sure how a user can find (so they can then upload to firebase) their player_id, so if anyone could point me in that direction it would be appreciated.
Reading through other questions, it seems like this would work. I just wanted to see if there were any like potential issues with this method or if there were any safer or easier ways to go about it.
回答1:
Yes this is possible, what you need to do is:
Create an OneSignal and Firebase Account for API-Keys
Add One Signal (just an example)
OneSignal.initWithLaunchOptions(launchOptions, appId: "your app id", handleNotificationReceived: { (notification) in }, handleNotificationAction: { (result) in let payload: OSNotificationPayload? = result?.notification.payload print(payload ?? "") }, settings: [kOSSettingsKeyAutoPrompt : false, kOSSettingsKeyInFocusDisplayOption: OSNotificationDisplayType.notification.rawValue])
save the push token/playerId to firebase (in users.id.onesignal for example)
OneSignal.promptForPushNotifications(userResponse: nil) OneSignal.idsAvailable({(_ userId, _ pushToken) in print("UserId:\(userId!)") if let pushToken = pushToken { print("pushToken:\(pushToken)") FIRDatabase.database().reference().child("users").child(User.sharedInstance.uid).child("onesignal").setValue([userId!: pushToken]) } })
When you have for every user an pushToken, you can send a notification to that playerId
FIRDatabase.database().reference().child("users").child(friendId).child("onesignal").observeSingleEvent(of: .value, with: {snapshot in if snapshot.exists() { for (playerId, _) in snapshot.value as! Dictionary<String, String> { OneSignal.postNotification(["headings": ["en": title], "contents": ["en": message], "include_player_ids": [playerId]]) } } })
This is not the full implementation and how to do it, but it will give you the right way I think.
来源:https://stackoverflow.com/questions/44246237/sending-push-notifications-from-ios-device-using-onesignal-firebase