Skip to content

Instantly share code, notes, and snippets.

@sugumura sugumura/app.module.ts
Last active Sep 5, 2018

Embed
What would you like to do?
IonicでのFirebaseによるプッシュ通知用のトークンを取得するサンプル。
// src/app/app.module.ts
import { Firebase } from '@ionic-native/firebase';
@NgModule({
//...
providers: [
Firebase,
],
//...
})
export class AppModule {}
// src/pages/sample/sample.ts
// import省略
@IonicPage()
@Component({
selector: 'page-sample',
templateUrl: 'sample.html',
})
export class SamplePage {
constructor(public platform: Platform, private firebase: Firebase,) {
this.platform.ready().then(() => {
if (this.platform.is('ios')) {
this.getPushTokenIOS()
.pipe(
mergeMap(token => this.requestDevice(token))
).subscribe({
next: response => {
// newsトピックを購読する
this.firebase.subscribe('news')
},
error: error => {
console.error(error);
}
});
}
if (this.platform.is('android')) {
this.getPushTokenAndroid()
.pipe(
mergeMap(token => this.requestDevice(token))
).subscribe({
next: response => {
// newsトピックを購読する
this.firebase.subscribe('news')
},
error: error => {
console.error(error);
}
});
}
})
}
getPushTokenIOS(): Observable<string|boolean> {
return this.hasPushPermission()
.pipe(
mergeMap((permission) => {
if (permission.isEnabled) {
return this.getPushToken();
} else {
return this.grantPushPermission()
.pipe(
mergeMap((grant) => {
return this.getPushToken();
}),
catchError(error => {
return of(false);
})
);
}
}),
)
}
getPushTokenAndroid(): Observable<string|boolean> {
return this.hasPushPermission()
.pipe(
mergeMap(permission => {
if (permission.isEnabled) {
return this.getPushToken();
} else {
return of(false);
}
})
)
}
private requestDevice(token: string): Observable<any> {
if (typeof token === 'string') {
// デバイストークンをサーバに保存する
// return Observable<any>
} else {
return _throw('push token get error');
}
}
private hasPushPermission(): Observable<{ isEnabled: boolean; }> {
return fromPromise(this.firebase.hasPermission());
}
private grantPushPermission(): Observable<any> {
return fromPromise(this.firebase.grantPermission());
}
private getPushToken(): Observable<any> {
return fromPromise(this.firebase.getToken());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.