精選

《十分鐘學程式》Firebase Push Notification - iOS Swift

現在已經是手機不離身的年代了,每天少則幾十通推播通知 (Push Notification),多則上百通,大家是否思考過這些推播是怎麼作業的嗎?好吧!我自己也沒想過,因為一切都是這麼的自然XD。

推播對一個 App 來說是不可缺少的,畢竟不可能要求使用者一直開著 App,那如何要在使用者在未開啟 App 時來達到傳遞訊息呢?這時就可以用飛鴿傳書,或是請刺客來幫忙傳遞...,如果這些方法都不喜歡的話,那可以考慮用用費時又浪費資源的推播 Push Notification 來達到這個目的。

說到這邊,是否想到如果要做到推播就需要自己先建一個 Server 才能做到,答案是否定的,因為我們有強大的 Google 幫大家都已經架設好了,而且是『免費的』這才是最重要的,因此 Firebase 就這樣產生了!!這次就要教大家如何使用 Firebase 來做到 iOS Push Notification。

在開始教學前需要做一些準備:
  1. 一台裝好 Xcode 的 Mac
  2. 一個付費的 Apple developer account,沒錯就是那個每年要繳 99美元的帳號
  3. 一個 Google 帳號
  4. 一杯夠大杯的咖啡 (What?)
上面這些東西都準備好的話!我們就開始上課嚕~~

這堂課會分 12 小節:
・Xcode 建立一個 Swift 專案
・設定 Apple Developer Account
・產生 CSR 檔
・上傳 CSR 檔
・準備 APNs (Apple Push Notifications) 認證
・Firebase 建立新專案
・Firebase Push Notification 設定
・撰寫設計一個支援 Firebase Push Notification 的 iOS App
・開啟 Push Notification 功能
・匯入 GoogleService-Info.plist
・初始化 Push Notification 設定
・測試 Firebase Push Notification

Xcode 建立一個 Swift 專案

1. 開啟 Xcode,選擇『Create a new Xcode project』來建立一個新的專案
2. 選擇『Single View App

3. 編輯 Product Name, 選擇要使用的帳戶

4. 選擇一個自己喜歡的資料夾存放這個專案吧!

5. 這裡要把 Display Name, Bundle Identifier 記下來等等會需要用到


設定 Apple Developer Account

1. 先開啟並登入 Apple Developer Account

2. 選擇左邊側欄的『Certificates, IDs & Profiles

3. 選擇『Identifiers』,注意左上角應該會有的按鈕,點擊他會帶你到另一個世界

4.   選擇 『App IDs』,然後點選 『Continue

5. 輸入剛剛記下來的 Display, Bundle Identifier,再次點選『Continue

6. 往下拉會發現有 『Push Notifications』,將他打勾,再次點選『Continue』(是要我確認幾次...)

7. 確認資料都沒有錯誤後,點選『Register

8. 這時候在 Identifiers 的地方就可以看到剛剛新建的 App,點擊他

9. 往下拉到 Push Notifications 的欄位,會發現顯示 Certificates(0),代表我們還沒有製作該 App Push Notification 所需的 Certificate。點擊『Configure

10. 點選『Create Certificate

11. 到這邊我們需要先打住,因為要先去產生一個 CSR 檔


產生 CSR 檔

1. 先按下 cmd + space 開啟 Spotlight,輸入『Keychain Access』,開啟 Keychain Access
2. 在 menu 選單上點選『鑰匙圈存取』>『憑證輔助程式』>『從憑證授權要求憑證...


3. 輸入『使用者電子郵件位址』,『一般名稱』,然後選擇『儲存到磁碟』,點選『繼續』
4. 選擇一個開心的資料夾存放這個 CSR 檔

上傳 CSR 檔

1. 回到 Apple developer account 頁面,選擇『Choose File

2. 選擇剛剛存下來的 CSR 檔

 3. 上傳成功後會看到後方有顯示剛剛上傳 CSR 檔的名稱,點選『Continue』(希望是最後一次確認的...)

4. 這時候就做好這個 App Push Notification 所需要的 Certificate,點選『Download

5. 一樣選一個風水寶地存放這個嬌貴的 Certificate 吧!


準備 APNs (Apple Push Notifications) 認證

1. 現在我們要做一個 APNs (Apple Push Notifications) 認證,這個認證是用來給 Firebase 連到 iOS App 。找到剛剛下載的 Certificate,連點兩下開啟認證檔案 (aps_development.cer) 加入到 Keychain Access

2. 打開 Keychain Access 在『我的憑證』內會看到這個認證檔。他應該會叫做

Apple Development IOS Push Services:<your.bundle.id>

點選認證檔左邊的展開鈕展開,會看到一個『專用密鑰』,在此專用密鑰點選右鍵,再按『輸出「XXX」

3. 這個專用密鑰為 p12 檔案格式,然後將這個 Certificates.p12 儲存起來。這時候所有的 Certificate 都已經準備完成,可以前往 Firebase 做設定嚕!!


Firebase 建立新專案

1. 開啟 Firebase 網頁,點選右上角的『Go to console


2. 點選『新增專案


3. 填一個自己喜歡的專案名稱吧!這邊我是直接用 Xcode 的 project name


4. 開啟『啟用這個專案的 Google Analytics (分析) 功能』,這個選項是一定要開啟的,如果沒有開啟事無法繼續的喔!


5. 設定一下 Google Analytics (分析) 帳戶名稱


6. 設定數據分析位置,然後把所有勾勾都打勾,就大力按下『建立專案』吧!


7. 成功建立好 Firebase 專案啦!!不過很可惜...這只是開始XD


Firebase Push Notification 設定

1. 開啟剛剛在 Firebase 建立新專案的頁面,點選『iOS』


2. 輸入『iOS 軟體包 ID (Bundle Identifier)』、『應用程式暱稱 (Display Name)』,然後按下『註冊應用程式


3. 點選『下載 GoogleService-Info.plist』,然後把這個 GoogleService-Info.plist 存起來等等會用到。一樣按下『繼續


4. 接著他會很好心的教你如何使用 CocoaPods 下載 Firebase 的 SDK,這邊看看就好,因為之後我會教XD,繼續下去吧~


5. 教你如何在 Xcode 初始化 Firebase,不過一樣看看就好嚕!


6. 這邊 Firebase 會想要驗證 iOS App 是否成功和 Firebase 連接,但是因為目前我們 iOS App 根本還沒建構完成,因此直接點『略過此步驟』就好啦!


7. 這時候會回到 Firebase Project 的主頁面,不過會發現多了一個剛剛新增的 iOS。直接點這個框框,會跳出另一個對話框,點擊上面的齒輪按鈕


8. 上方標籤頁選擇『Cloud Messaging』,然後在下方 APN 憑證的地方點選『上傳



9. 點選『瀏覽』,選擇剛剛 Keychain Access 匯出的憑證 (Certificates.p12)


10. 確認檔案沒有問題後,直接點選『上傳


11. 上傳成功後會在 APN 憑證看到


12. 到這邊 Firebase Push Notification 的所有設定都已經完成嚕!這個 Demo 是使用 Development APNs Certificate,但是如果 App 要上架至 App Store 是需要把 APNs Certificate 存到 Firebase 的 Production APNs 內喔!


撰寫設計一個支援 Firebase Push Notification 的 iOS App

1. 我們要先將 Firebase SDK 加入到 Xcode Project,這邊我們使用最簡單的 CocoaPods。如果不知道如何使用的人先去另外兩篇教學學習嚕 (《十分鐘學程式》CocoaPods 安裝教學《十分鐘學程式》CocoaPods 使用第三方資料庫教學)


2. 開啟慣用的 Terminal,指向剛剛一開始我們建立的 Xcode Swift Project,然後就開始 Command 世界嚕!先初始化 CocoaPods
 pod init

3. 開始編輯 CocoaPods Podfile
 vim Podfile

4. Podfile 一開始應該會長這樣
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

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

  # Pods for Use CocoaPods Test Project

end

5. 加入我們要使用的 Firebase SDK
 pod 'Firebase/Analytics'
 pod 'Firebase/Messaging'

6. 加入之後 Podfile 會長這樣
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'Use CocoaPods Test Project' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
  # Pods for Use CocoaPods Test Project

end

7. 存檔後,就要開始用 CocoaPods 來安裝 Firebase SDK 嚕!輸入
 pod install

8. 下載並且安裝好後 CocoaPods 會提醒已經幫我們建立了另個 .xcworkspace,之後我們要開啟這個專案就要用這個 xcworkspace 開啟喔!不然會找不到 CocoaPods 幫我們下載的第三方 Library
9. 到 Xcode Swift Project 的目錄下找到 .xcworkspace,並且打開它吧!

開啟 Push Notification 功能

1. 在左邊 TARGETS 標籤地方選擇自己的專案,接著在上方標籤地方選擇『Signing & Capabilities』,然後會在下方看到一個+,用力的點下去吧!


2. 找到『Push Notifications』點兩下


3. 接著會在下方看到 Push Notifications 就代表這個專案已經開啟推播功能


匯入 GoogleService-Info.plist 

1. 找出剛剛在 Firebase 下載的 GoogleService-Info.plist 檔,從 Finder 拉到 Xcode 內


2. 記得把『Copy items if needed』打勾


3. 成功匯入 GoogleService-Info.plist 會在 Xcode Project Folder 看到


初始化 Push Notification 設定

1. 耗了這麼多時間跟本來沒 coding 到,大家是否手都癢癢的呢XD,現在終於要開始嚕~開啟 AppDelegate.swift

2. 先 import 兩個我們需要的 Library
import UserNotifications
import Firebase

3. 在 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:) 內加入以下 code
// Initiazlie Firebase
FirebaseApp.configure()
// Set Firebase messaging delegate
Messaging.messaging().delegate = self

// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
if #available(iOS 10.0, *) {
  UNUserNotificationCenter.current().delegate = self

  let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (state, error) in
  }
} else {
  let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()

4. 在 AppDelegate 最下面加入以下 code
@available(iOS 10,*)
extension AppDelegate: UNUserNotificationCenterDelegate {
    
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
    let userInfo = notification.request.content.userInfo
    print("willPresent userInfo: \(userInfo)")
        
    completionHandler([.badge, .sound, .alert])
  }
    
  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
    let userInfo = response.notification.request.content.userInfo
    print("didPresent userInfo: \(userInfo)")
        
    completionHandler()
  }
}

extension AppDelegate: MessagingDelegate {
    
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
        
    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
  }
    
  func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
  }
}

5. 到這邊 iOS App 也已經都完成嚕!!將 App 安裝到自己的 iPhone 做測試吧!App 第一次開啟會詢問是否開啟推播通知,一定要按『允許』喔!!不然會收不到推播啦!

測試 Firebase Push Notification

1. 回到 Firebase console,選擇剛剛建立的專案。左邊的側欄會看到有 Cloud Messaging 選項,給他點下去。點選『新增通知』


2. 輸入『通知標題』、『通知文字』後,下一步


3. 應用程式選擇剛剛建立的 iOS App,下一步


4. 排定時間直接選擇現在,因為我們現在馬上就要測試啦!一樣下一步


5. 設定轉換事件(通用)在這邊我們不需要做設定,直接按下『審查』


6. 終於到了這一步,見證奇蹟的時刻~帶著緊張又刺激的心情按下『發佈』吧


7. 登愣!收到 Firebase 傳過來的 Push Notification 啦!


〖 總結 〗

Push Notification 是現在 App 不可缺少的功能,因為畢竟在使用者沒有開啟 App 時還是有很多訊息想要通知,例如:軟體更新、或是有任何活動等,都可以透過 Push Notification 來達到此功能。


留言

熱門文章