{ "message": { "webpush": { "notification": { "title": "Fish Photos 🐟", "body": "Thanks for signing up for Fish Photos! You now will receive fun daily photos of fish!", "icon": "firebase-logo.png", "image": "guppies.jpg", "data": { "notificationType": "fishPhoto", "photoId": "123456" }, "click_action": "https://example.com/fish_photos", "actions": [ { "title": "Like", "action": "like", "icon": "icons/heart.png" }, { "title": "Unsubscribe", "action": "unsubscribe", "icon": "icons/cross.png" } ] } }, "token": "<APP_INSTANCE_REGISTRATION_TOKEN>" } }
like
unsubscribe
// Retrieve an instance of Firebase Messaging so that it can handle background messages. const messaging = firebase.messaging(); // Add an event listener to handle notification clicks self.addEventListener('notificationclick', function(event) { if (event.action === 'like') { // Like button was clicked const photoId = event.notification.data.photoId; like(photoId); } else if (event.action === 'unsubscribe') { // Unsubscribe button was clicked const notificationType = event.notification.data.notificationType; unsubscribe(notificationType); } event.notification.close(); });
var registrationToken = 'YOUR_REGISTRATION_TOKEN'; var message = { data: { score: '850', time: '2:45' }, token: registrationToken }; admin.messaging().send(message) .then((response) => { console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', error); });
var registrationTokens = [ 'YOUR_REGISTRATION_TOKEN_1', // ... 'YOUR_REGISTRATION_TOKEN_n' ]; admin.messaging().subscribeToTopic(registrationTokens, topic) .then(function(response) { console.log('Successfully subscribed to topic:', response); }) .catch(function(error) { console.log('Error subscribing to topic:', error); });
onMessageReceived()
onTokenRefresh()
@Override public void onMessageReceived(RemoteMessage remoteMessage) { if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); } } /** * Schedule a job using FirebaseJobDispatcher. */ private void scheduleJob() { FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); Job myJob = dispatcher.newJobBuilder() .setService(MyJobService.class) .setTag("my-job-tag") .build(); dispatcher.mustSchedule(myJob); } /** * Perform and immediate, but quick, processing of the message. */ private void handleNow() { Log.d(TAG, "Short lived task is done."); }
connectToFCM()
content-available
application(_:didRegisterForRemoteNotificationsWithDeviceToken:)
application(_:didFailToRegisterForRemoteNotificationsWithError:)
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Oh no! Failed to register for remote notifications with error \(error)") }
didRegister...
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { var readableToken: String = "" for i in 0..<deviceToken.count { readableToken += String(format: "%02.2hhx", deviceToken[i] as CVarArg) } print("Received an APNs device token: \(readableToken)") }
application.registerForRemoteNotifications()
UNUserNotificationCenter.current().getNotificationSettings { (settings) in print("Alert setting is \(settings.alertSetting == UNNotificationSetting.enabled ? "enabled" : "disabled")") print("Sound setting is \(settings.soundSetting == UNNotificationSetting.enabled ? "enabled" : "disabled")") }
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in if (error != nil) { print("I received the following error: \(error)") } else if (granted) { print ("Authorization was granted!") } else { print ("Authorization was not granted. :(") } }
curl 7.47.1 (x86_64-apple-darwin15.6.0) libcurl/7.47.1 OpenSSL/1.0.2f zlib/1.2.5 nghttp2/1.8.0 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp Features: IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets
.p12
openssl pkcs12 -in MyApp_APNS_Certificate.p12 -out myapp-push-cert.pem -nodes -clcerts
ab8293ad24537c838539ba23457183bfed334193518edf258385266422013ac0d
> curl --http2 --cert ./myapp-push-cert.pem \ -H "apns-topic: com.example.yourapp.bundleID" \ -d '{"aps":{"alert":"Hello from APNs!","sound":"default"}}' \ https://api.development.push.apple.com/3/device/ab8293ad24537c838539ba23457183bfed334193518edf258385266422013ac0d
--cert
.pem
apns-topic
userNotificationCenter(_:willPresent:withCompletionHandler:)
completionHandler([.alert])
firInstanceIDTokenRefresh
func application(_ application: UIApplication, didFinishLaunchingWithOptions // ... printFCMToken() // This will be nil the first time, but it will give you a value on most subsequent runs NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil) application.registerForRemoteNotifications() //... } func printFCMToken() { if let token = FIRInstanceID.instanceID().token() { print("Your FCM token is \(token)") } else { print("You don't yet have an FCM token.") } } func tokenRefreshNotification(_ notification: NSNotification?) { if let updatedToken = FIRInstanceID.instanceID().token() { printFCMToken() // Do other work here like sending the FCM token to your server } else { print("We don't have an FCM token yet") } }
> curl --header "Content-Type: application/json" \ --header "Authorization: key=AU...the rest of your server key...s38txvmxME-W1N4" \ https://fcm.googleapis.com/fcm/send \ -d '{"notification": {"body": "Hello from curl via FCM!", "sound": "default"}, "priority": "high", "to": "gJHcrfzW2Y:APA91...the rest of your FCM token...-JgS70Jm"}'
{"multicast_id":86655058283942579,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1486683492595106961%9e7ad9838bdea651f9"}]}
InvalidRegistration
priority
high
"content-available":
"content_available": true
"content-available"
「FCM を見つけるまで、効果的な通知ソリューションを探すことはできませんでした。……機能が豊富でパフォーマンスも安定しており、導入も簡単な FCM は最高のソリューションです」 Alibaba.com モバイル、ディレクター、Zou Yu 氏
「Firebase Cloud Messaging は私たちの要件に完璧に一致しました」 AliExpress、ディレクター、Lijun Chen 氏
「初期実装はとても簡単でした。実際に 1 日で終わってしまったほどです」 デベロッパー、Filip Procházka 氏
sendNotificationToUser("puf", "Hi there puf!");
public static void sendNotificationToUser(String user, final String message) { Firebase ref = new Firebase(FIREBASE_URL); final Firebase notifications = ref.child("notificationRequests"); Map notification = new HashMap<>(); notification.put("username", user); notification.put("message", message); notifications.push().setValue(notification); }
notificationRequests $pushid message: "Hello there" username: "puf"
var firebase = require('firebase'); var request = require('request'); var API_KEY = "..."; // Your Firebase Cloud Server API key firebase.initializeApp({ serviceAccount: ".json", databaseURL: "https://.firebaseio.com/" }); ref = firebase.database().ref(); function listenForNotificationRequests() { var requests = ref.child('notificationRequests'); ref.on('child_added', function(requestSnapshot) { var request = requestSnapshot.val(); sendNotificationToUser( request.username, request.message, function() { request.ref().remove(); } ); }, function(error) { console.error(error); }); }; function sendNotificationToUser(username, message, onSuccess) { request({ url: 'https://fcm.googleapis.com/fcm/send', method: 'POST', headers: { 'Content-Type' :' application/json', 'Authorization': 'key='+API_KEY }, body: JSON.stringify({ notification: { title: message }, to : '/topics/user_'+username }) }, function(error, response, body) { if (error) { console.error(error); } else if (response.statusCode >= 400) { console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); } else { onSuccess(); } }); } // start listening listenForNotificationRequests();
String username = "puf"; FirebaseMessaging.getInstance().subscribeToTopic("user_"+username);