Ionic Framework で cordova-plugin-safariviewcontroller を使う
- 2018 2/24
- カテゴリー : Mobile App Framework
- ionic
- コメントを書く
Ionic Framework で cordova-plugin-safariviewcontroller を使ってみたので、サンプルコードをご紹介します。
- Ionic Native – Safari View Controller
- EddyVerbruggen/cordova-plugin-safariviewcontroller: Forget InAppBrowser for iOS – this is way better for displaying read-only web content in your PhoneGap app
SafariViewController インストール
cordova plugin と npm module をそれぞれインストールします。
ionic cordova plugin add cordova-plugin-safariviewcontroller npm install --save @ionic-native/safari-view-controller |
SafariViewController の使い方
SafariViewController で URL を開くサンプルコードは以下のような感じです。
// src/pages/home/home.ts export class HomePage { constructor(public navCtrl: NavController, public platform: Platform, private iab: InAppBrowser, private safariViewController: SafariViewController) { } openUrl(url: string) { // SafariViewController のサポートプラットフォームは Android, iOS のみ if (this.platform.is('android') || this.platform.is('ios')) { this.safariViewController.isAvailable() .then((available: boolean) => { if (available) { this.safariViewController.show({ url: url, }) .subscribe((result: any) => { if (result.event === 'opened') console.log('Opened'); else if (result.event === 'loaded') console.log('Loaded'); else if (result.event === 'closed') console.log('Closed'); }, (error: any) => console.error(error) ); } else { // SafariViewController を利用できない場合、フォールバック this.openUrlWithFallbackBrowser(url); } } ); } else { // SafariViewController を利用できない場合、フォールバック this.openUrlWithFallbackBrowser(url); } } openUrlWithFallbackBrowser(url: string) { // use fallback InAppBrowser this.platform.ready().then(() => { const browser = this.iab.create(url, '_system'); browser.show(); }); } } |
上記のサンプルコードを2点補足します。
1点目は、cordova-plugin-safariviewcontroller のサポートプラットフォームは Android, iOS のみなので、if (this.platform.is(‘android’) || this.platform.is(‘ios’)) で利用できる環境か判定しています。
2点目は、SafariViewController を利用できない環境には InAppBrowser を使うことでフォールバックしています。
詳しい実装は以下の pull request を参考にしてください。
また、InAppBrowser については、[Ionic] InAppBrowser で URL をデフォルトブラウザで開く使い方 | CodeNote も併せて参考にしてください。
以上、Ionic Framework で外部 URL を開くときは SafariViewController をメインで使いたい、現場からお送りしました。