我已经按照 Ionic 3 文档中关于推送通知的说明进行操作。
当我尝试在后台发送通知和我的应用程序时,我无法触发"通知"事件,因此我无法浏览特定页面。
但是,当我的应用处于前台时,"通知"事件会自动触发。
我使用:
-
Ionic 3作为移动框架
-
Firebase Cloud Messagins 作为消息服务
-
Laravel与larave-fcm插件发送消息
后端 - 用于向 Firebase 推送消息的 Laravel 代码
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)->setContentAvailable(true);
$notificationBuilder = new PayloadNotificationBuilder('Hello');
$notificationBuilder->setBody('Hello world')->setSound('default');
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData(['custom' => 'test']);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$token = "token";
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
$success = $downstreamResponse->numberSuccess();
$failure = $downstreamResponse->numberFailure();
$modification = $downstreamResponse->numberModification();
echo 'Success: '.$success;
echo "<br>";
echo 'Failure: '. $failure;
echo "<br>";
echo 'Modification: '.$modification;
print_r($downstreamResponse->tokensToDelete());
echo "<br>";
print_r($downstreamResponse->tokensToModify());
echo "<br>";
print_r($downstreamResponse->tokensToRetry());
echo "<br>";
print_r($downstreamResponse->tokensWithError());
前端 - 我在 app.component.ts 上的离子应用程序构造函数
constructor(private translate: TranslateService, private platform: Platform, settings: Settings, private config: Config, private statusBar: StatusBar, private splashScreen: SplashScreen, public push: Push, public alertCtrl: AlertController, public storage: Storage, private backgroundMode: BackgroundMode) {
this.initTranslate();
this.platform.ready().then(() => {
if(!this.backgroundMode.isActive) {
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
} else {
this.backgroundMode.disable();
this.backgroundMode.setDefaults({silent: true});
this.backgroundMode.enable();
}
this.pushSetup();
this.storage.get('test').then((val) => {
if(val == 'news'){
this.nav.setRoot(TabsPage);
}
});
});
}
函数 pushSetup((
pushSetup() {
const options: PushOptions = {
android: {
senderID: '10524067XXXXX'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
if(notification.additionalData.foreground){
let myAlert = this.alertCtrl.create({
title: 'Push',
message: JSON.stringify(notification)
});
myAlert.present();
} else {
this.storage.set('test', 'news');
}
});
pushObject.on('registration').subscribe((registration: any) => {
console.log(registration);
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
我从中找到了答案 这里。
我应该像这样发送到 fcm
{
"data" : {
"title": "Test Notification",
"body": "This offer expires at 11:30 or whatever",
"notId": 10,
"surveyID": "ewtawgreg-gragrag-rgarhthgbad"
}
}
在laravel fcm上,只需在PayloadDataBuilder的addData函数上设置标题,正文,notId。