
実機にリモート通知を送ってみるやり方です。
手順の順番を時系列で書いているわけではないです。それぞれの箇所ごとにまとめて書いています。わかりにくかったら申し訳ありません。
まず、ローカルプッシュ通知とリモートプッシュ通知の違いですが、
ローカルプッシュ通知
→ネットに接続していなくても通知ができる ex)アラーム
リモートプッシュ通知
→ネットに接続してないといけない ex)ニュース速報、緊急地震速報
目次
リモートプッシュ通知の流れ
- Appleが提供するpush通知サーバー(APNs)に通知の送信を依頼する。
- Firebaseから送信する場合は、APNs経由で送信
ライブラリのインポート
pod 'Firebase/Core'
pod 'Firebase/Messaging'
通知を実装したいアプリにこの2つのライブラリをインポートしてください。
Firebaseでの作業
Firebaseで新しいプロジェクトを作ってください。
GoogleService-Info.plistを入れるなど一連の作業を終わらせてください。
fa-chevron-circle-rightAPNs証明書のアップロード
コンソール画面に進み、[設定マーク]から「プロジェクトの設定」をクリック。
「Cloud Messaging」タブをクリック。してスクロールし、「開発用 APNs 証明書がありません」のところに.「p12」証明書をupしてください。
コードの記述
AppDelegate.swiftに
import FirebaseMessaging
import UserNotifications
import Firebase
この3つのライブラリを追加。
そしたら
var notificationGranted = true
を追記。
その後、didFinishLaunchingWithOptions内に以下のコードを追記
FirebaseApp.configure()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}application.registerForRemoteNotifications()
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound])
{
(granted, error) in
self.notificationGranted = granted
if let error = error {
print("granted, but Error in notification permission:\(error.localizedDescription)")
}}return true
さらに以下のメソッドも追記
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print message ID.
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}// Print full message.
print(userInfo)
}func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Print message ID.
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}// Print full message.
print(userInfo)completionHandler(UIBackgroundFetchResult.newData)
}
すると、このようなエラー
「'AppDelegate' is not convertible to 'UNUserNotificationCenterDelegate'; did you mean to use 'as!' to force downcast?」(UNUserNotificationCenterDelegateがプロトコルとして宣言されていないという意味)
が出ていると思うので、
以下のコードをエクステンションとしてコードの一番下に追記。
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfoif let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}print(userInfo)
completionHandler([])
}func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}print(userInfo)
completionHandler()
}
}
Xcodeでの作業
【TARGETS】→【Signing & Cabilities】→【+Capability】から、「Background Modes」と「Push Notifications」を選択して追加し、「Remote notifications」のチェックを入れてください。
キーチェーンアクセスでの作業
「キーチェーンアクセス」というアプリケーションを開いて、画面左上の「キーチェーンアクセス」→「証明書アシスタント」→「証明局に証明書を要求」をクリック。
そうするとこのようなダイアログが出てきます。アドレスを入力し、「ディスクに保存」を選択し、「鍵ペア情報を指定」にチェック。「続ける」をクリック。
その後は「保存」「続ける」「完了」の順で進めてください。
Apple developerでの作業
Apple developerにログインして、Certificates, Identifiers & Profilesまで行ってください。
青い「+」をクリック。
そうしたら「iOS App Development」にチェックを入れ、「Continue」。
「Choose File」からCertificateSigningRequest.certSigningRequestを選択して「Continue」。
この後は「download」をクリックして、DLされたものをダブルクリックすればOKです。それでキーチェーンアクセスに置かれます。
fa-chevron-circle-rightApp IDsの作成
次にApp IDsを作ります。
左のタブから「Identifiers」を選択して、同じように青い「+」をクリック。
「App IDs」にチェック入れて「Continue」
「Description」にアプリ名を入れ、「Bundle ID」にバンドルIDを入れます。
スクロールして「Push Notifications」にチェック。で「Continue」→「register」これでApp IDsの作成は完了です。
fa-chevron-circle-rightデバイスの登録
左のタブから「Devices」をクリック例のように青い「+」をクリック。
するとこのような画面が出ます。
「Device Name」と「Device ID (UDID)」を入力して「Continue」してください。
UDIDはMacとiPhoneを繋いで、「システム情報」アプリケーションから確認できます。
参考:UDID確認の仕方
fa-chevron-circle-rightプロビジョニングファイルの作成
左のタブの「Profiles」を選び青い「+」をクリック。
そしたら「iOS App Development」にチェック。「Continue」。
あなたの作ったApp IDsを選択して「Continue」
その後は「Select Certificates」、「Select Device」などを聞かれますが、「Select All」で良いでしょう。
そうしたら「Provisioning Profile Name」を適当に付けて「generate」→「download」。DLしたものをダブルクリックで完了です。
すると、キーチェーンアクセスで確認できるはずです。
fa-chevron-circle-rightAPNs SSLを作成
Certificatesタブ→青い「+」→「iOS Apple Push Notification service SSL (Sandbox)」にチェックで「Continue」。
作ったApp IDsを選択し「Continue」→「Choose File」からCertificateSigningRequest.certSigningRequestを選択して「Continue」→「download」→ダブルクリック。
そしたらキーチェーンアクセスに戻り、対象の証明書を副クリック→「〜を書き出す」をクリック。
その後は流れに身を任せて、「保存」→「OK」→パスワード入力
上記が全て完了したら
登録したデバイスをMacに繋ぎ、firebaseの【拡大】タブの「Cloud Messaging」→「Send your first message」
そうしたら、必要項目を記入して「次へ」
アプリを選択して「次へ」→スケジュールを「現在」で「次へ」→「確認」→「公開」
これで実機にプッシュ通知がきたと思います。