LoginSignup
8
7

More than 5 years have passed since last update.

Firebaseの通知を受け取る最新の方法 (2018-05-15 時点)

Last updated at Posted at 2018-05-14

1. 証明書の設定

こちらを参考。

自分の環境では、 Provision Profile doesn't include signing certificate
というふざけたエラーが出て、開発者証明書がきちんと読み込めなかったので、キーチェーンのログイン項目の証明書をすべて削除(自己責任で行ってください)
https://stackoverflow.com/questions/39568112/provision-profile-doesnt-include-signing-certificate

2. Firebaseのコンソールでやること

0. GoogleService-Info.plistをダウンロードしておく

自然な流れでダウンロードできるはず。

1. 先程の記事(https://qiita.com/natsumo/items/d5cc1d0be427ca3af1cb )中の7.で作成したp12ファイルをブチ込む

Project settings -> CLOUD MESSAGINGで設定

スクリーンショット 2018-05-14 18.23.35.png

ここで証明書をアップロード

スクリーンショット 2018-05-14 18.22.53.png

2. SERVER_KEYをメモ

CLOUD MESSAGINGの上の方にあるserver keysをメモしておく

3. Podfileをいじる

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'TestFirebase' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  pod 'Firebase/Core'
  pod 'Firebase/Messaging'

  # Pods for notification-test

end

4. XCode上でやること

1. 2-0 で追加したGoogleService-Info.plistをxcodeのプロジェクトに追加する。

2. GoogleService-Info.plistにserver keysをぶち込む

スクリーンショット 2018-05-14 18.28.10.png
(安心してください!!!見えてないですね!!!)

3. 忘れがちなやつ

スクリーンショット 2018-05-17 15.47.01.png

4. コードを書く

import UIKit
import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        Messaging.messaging().delegate = self as MessagingDelegate
        UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted: Bool, error: Error?) in
        }
        application.registerForRemoteNotifications()
        FirebaseApp.configure()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}


extension AppDelegate: UNUserNotificationCenterDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    }

    // 停止中に通知がきて、通知経由で開いた場合
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

    // 起動中に通知がきた場合
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        completionHandler([])
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase Registration Token: \(fcmToken)")
    }
}

備考

  • MessagingDelegateが何をしてくれるものなのかはまだ調べていない。
  • 動かねえぞ(゚Д゚)ゴルァ!というご相談は歓迎です。 twitter: _kentrino まで
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7