iOS Push Notifications + 模擬器

Xcode 11.4 推出新功能,可以透過 simctl 指令發送 Push Notifications 到 iOS 模擬器 (Emulator)。不在一定要透過後端程式才能發送。大大地降低開發時的時間成本。

Xcode 11.4 推出新功能,可以透過 simctl 指令發送 Push Notifications 到 iOS 模擬器 (Simulator)。不在一定要透過後端程式才能發送。大大地降低開發時的時間成本。

完整的程式碼可以在 下載。

確認 Xcode 版本

首先最重要是要確認 Xcode 的版本是不是 Xcode 11.4 或以上。如果不是,請先升級再繼續閱讀。

建立 Xcode 專案

首先建立 Xcode 專案。建立後,在 AppDelegate.swift 引入 UserNotifications framework。

import UserNotifications

在 AppDelegate.swift 的 application(_:didDiscardSceneSession:),向使用者請求 Notifications 權限。

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().delegate = self

    let options: UNAuthorizationOptions = [.alert, .sound, .badge]
    UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, error) in
        if granted {
            print("Permission is granted")
        } else if let error = error {
            print("Permission is not granted: \(error)")
        }
    }

    return true
}

然後實作 UNUserNotificationCenterDelegate 來接收 Push Notifications。在 AppDelegate.swift 下加上以下程式碼。

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let options = UNNotificationPresentationOptions(arrayLiteral: .alert, .sound, .badge)
        completionHandler(options)
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
}

最後將 AppDelegate 設給 UNUserNotificationCenter

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
}

專案已經可以接受 Push Notifications 了。執行專案,可以看到 App 會請求 Notifications 權限。

Ask for the permission of Push Notifications
Ask for the permission of Push Notifications

發送 Push Notifications 給模擬器

Xcode 11.4 的 Release Note 提到如何用 simctl 發送 Push Notifications。

% xcrun simctl push <device> com.example.my-app ExamplePush.apns

指令中的參數:

  • <device>:指模擬器裝置的 Identifier。先決定好你要哪個模擬器,然後可以由下圖的方式找到。
  • com.example.my-app:是要接受推送通知的 App 的 Bundle Identifier。
  • ExamplePush.apns:是 Push Notifications 的內容。
Find Simulator's Identifier
Find Simulator’s Identifier

本章專案的 Bundle Identifier 是 com.waynestalk.PushNotificationTest。

然後要準備 Push Notifications 的內容檔。格式在這邊有詳細的說明。這裡就不詳細解說了。在專案裡面已經有個簡單的 Push Notifications 內容檔 (notification.apns)。

{
    "aps": {
        "alert": "Hello Wayne's Talk!",
        "sound": "default",
        "badge": 1
    }
}

所有的東西都準備好了,用下方的指令來發送 Push Notifications 給專案 App。記得專案要先跑起來喔!

% xcrun simctl push F3ED42DB-9DF0-4680-A260-B373A0ACFDC0 com.waynestalk.PushNotificationTest notification.apns
Send push notification with simctl
Send push notification with simctl

不需要後湍就可以送出 Push Notifications 通知真的很方便。不過每次打指令也是很麻煩的。在 notification.apns 裡,把專案的 Bundle Identifier 加在 Simulator Target Bundle。

{
    "Simulator Target Bundle": "com.waynestalk.PushNotificationTest",
    "aps": {
        "alert": "Hello Wayne's Talk!",
        "sound": "default",
        "badge": 1
    }
}

然後將 notification.apns 直接拖拉到模擬器上,就可以發送 Push Notifications。

Send a push notification by dragging APNs
Send a push notification by dragging APNs

結語

Xcode 11.4 加上這個好用的功能,對開發者是一大福音。對於沒有後端可以發送 Push Notifications 的人,提供了發送的管道。而對於有後台的人,卻提供更省時的方式可以測試 App。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You May Also Like
Photo by Alex Alvarez on Unsplash
Read More

Dispatch Queue 教學

GCD 提供有效率的並行處理,讓我們不需要直接管理多執行緒。它的 Dispatch Queues 可以循序地(serially)或是並行地(concurrently)執行任務。我們只需要將要並行的程式當作任務提交到 dispatch queues 就可以了。
Read More
Photo by Florinel Gorgan on Unsplash
Read More

如何製作一個 XCFramework

XCFramework 讓你可以將 iPhone、iPhone 模擬器等多的不同平台的二進位碼打包到一個可發佈的 .xcframework 檔。你只需要為你的 Framework 產生出一個 .xcframework 檔,就可以支援多種平台。
Read More
Photo by Fabian Gieske on Unsplash
Read More

SwiftUI @State & @Binding 教學

SwiftUI 推出了兩個 Property Wrapper – @State and @Binding。利用它們可以達到變數的 Two-way Binding 功能。也就是當變數的值改變時,它會重新被顯示。本章藉由製作一個 Custom View 來展示如何使用 @State 和 @Binding。
Read More