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


# 1. 証明書の設定
https://qiita.com/natsumo/items/d5cc1d0be427ca3af1cb

こちらを参考。

自分の環境では、 `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で設定
<img width="559" alt="スクリーンショット 2018-05-14 18.23.35.png" src="https://qiita-image-store.s3.amazonaws.com/0/117143/4ad22ca2-0e25-78ce-73c2-ee92c06a4502.png">

#### ここで証明書をアップロード
<img width="980" alt="スクリーンショット 2018-05-14 18.22.53.png" src="https://qiita-image-store.s3.amazonaws.com/0/117143/685a03ea-65c5-10ec-2202-9ee907d136ef.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をぶち込む
<img width="388" alt="スクリーンショット 2018-05-14 18.28.10.png" src="https://qiita-image-store.s3.amazonaws.com/0/117143/4cc135e3-03c9-8c8d-6fd0-63bc1634c820.png">
（安心してください！！！見えてないですね！！！）

### 3. 忘れがちなやつ
![スクリーンショット 2018-05-17 15.47.01.png](https://qiita-image-store.s3.amazonaws.com/0/117143/1afb0bac-766d-dff9-022c-7f553599cc8a.png)


### 4. コードを書く

```swift
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 まで