Skip to content

Instantly share code, notes, and snippets.

@sugumura
Last active September 5, 2018 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugumura/f9bf1a18768fc5275828aca76a6e9934 to your computer and use it in GitHub Desktop.
Save sugumura/f9bf1a18768fc5275828aca76a6e9934 to your computer and use it in GitHub Desktop.
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