SwiftUI – iOS10本地推送通知教程UserNotifications在Swift中的實現方式

簡介

消息推送相信在很多人的眼裡都不陌生了吧?像即時聊天微信,好友發信息給你時會在頂部彈下小窗口提醒你。也像是在影院APP預訂了電影票,在開場前一小時你也會收到提醒。這類推送是需要經過後端發送請求的,需要服務器發送推送請求,又或者使用如極光推送等第三方渠道。

那麼如果我們的APP不需要連網呢?這是不是就不能使用消息推送了?不是的,蘋果還提供給我們本地消息通知服務,即便APP不連網也能使用,功能也很強大可靠。本地時鐘的應用場景很廣泛,例如手機上的時鐘、日曆等。

那麼你知道如何去實現它嗎?這篇文章將告知你答案,同時以兩個小案例作為例子,以便更好地去理解它。

筆者環境

Xcode – Version 11.5 (11E608c)

Swift – version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53).

權限獲取

UserNotifications 是 iOS10 推出來的框架,因此你只能在 10 或以上的版本使用它。推送服務和以往一樣,也是需要用戶授權的,當用戶同意後才能正常註冊消息通知,當用戶拒絕時應該引導用戶去打開APP的通知權限。利用requestAuthorization方法彈出並獲取通知權限,接收的參數options是具體的授權選項,一般有彈窗、未讀數量圖標和聲音即可,並在回調閉包中可以獲取授權結果和錯誤。

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (status, err) in
    if !status {
    		print("用戶不同意授權通知權限")
        return
    }
}

status 為布爾類型,true 表示用戶同意,false 即拒絕。在此種情況下,我們可以使用彈窗去引導用戶去打開通知權限,需要明確告知用戶打開後有什麼好處,如果關閉會造成什麼影響等等。如果讓用戶手動打開設置,找到APP,為APP開啟權限,這樣未免太過複雜,所幸的是可以通過以下代碼為用戶直接跳轉至該應用的權限設置中心。

guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, completionHandler: nil)
}

應彈窗提示用戶,待用戶同意後才跳轉至設置,不然容易引起用戶的不滿心理。

觸發器

本地消息通知一般有以下三種類型的觸發器,它們都是繼承於類UNNotificationTrigger

  1. UNTimeIntervalNotificationTrigger – 在經過特定的時間後觸發本地消息推送;
  2. UNCalendarNotificationTrigger – 在特定的時間點觸發本地消息推送;
  3. UNLocationNotificationTrigger – 在進入或離開特定的地理位置時觸發本地消息推送。

UNTimeIntervalNotificationTrigger

手機上的時鐘用過吧,裏面的計時器功能就可以用UNTimeIntervalNotificationTrigger實現,比如開始計時30分鐘,那麼在計時器完成的時候就是使用通知提醒。

那麼設置在經過特定的時間後觸發本地消息推送,一般都經由以下幾個步驟:

  1. 首先創建UNMutableNotificationContent類,設定標題和內容,如果你有子標題還可以設置子標題,一般很少見到會設置子標題的應用。
  2. 創建觸發器,這裡就是UNTimeIntervalNotificationTrigger,設定執行秒數和是否循環通知。
  3. 創建通知請求UNNotificationRequest,這裡需要指定通知的identifier,內容和觸發器,至於identifier,你可以隨意定義。
  4. 最後將通知請求添加到系統的通知中心UNUserNotificationCenter即可。

例子,創建一個通知,在5秒後執行消息推送。實例代碼展示如下:

let content = UNMutableNotificationContent()
content.title = "添加朋友 對着月亮敲代碼"
//content.subtitle = "子標題"
content.body = "公眾號 gh_6a83a7c19315"
content.badge = 1

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "Notification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { err in
    err != nil ? print("添加本地通知錯誤", err!.localizedDescription) : print("添加本地通知成功")
}

有一處小 Tips,UNTimeIntervalNotificationTrigger創建時的repeats選項,如果你設定為循環通知時,即需要每隔N秒觸發一次通知,那麼你必須至少設置為60秒的時間間隔,如若低於60秒,你將會得到這樣一條錯誤。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'
*** First throw call stack:
(
	0   CoreFoundation                      0x00007fff23c7127e __exceptionPreprocess + 350
	1   libobjc.A.dylib                     0x00007fff513fbb20 objc_exception_throw + 48
	2   CoreFoundation                      0x00007fff23c70ff8 +[NSException raise:format:arguments:] + 88
	3   Foundation                          0x00007fff256e9b51 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191
	4   UserNotifications                   0x00007fff2c7dfc7c -[UNTimeIntervalNotificationTrigger _initWithTimeInterval:repeats:] + 277

UNCalendarNotificationTrigger

手機上的日曆用過吧,在新建日程的時候,你可以選擇一個提醒時間,這樣它就會在你設定的提醒時間提醒你,這種情況就很適合用UNCalendarNotificationTrigger去實現。

舉個例子,我們要在每晚7點提醒用戶看公眾號。

let content = UNMutableNotificationContent()
content.title = "添加朋友 對着月亮敲代碼"
//content.subtitle = "子標題"
content.body = "公眾號 gh_6a83a7c19315"
content.badge = 1

let dateComponents = DateComponents(hour: 19) // 1
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // 2
let request = UNNotificationRequest(identifier: "Notification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { err in
    err != nil ? print("添加本地通知錯誤", err!.localizedDescription) : print("添加本地通知成功")
}

1 – 創建時間元件,19點即為晚上7點

2 – 創建UNCalendarNotificationTrigger對象,並將dateComponents賦值到dateMatching,repeats為true,重複在每天19點收到通知提醒。

UNLocationNotificationTrigger

這個觸發器不在此篇文章講述,留給你們自己去實現和測試結果。

圖標

還記得剛剛設置的屬性badge嗎,我們設置值為1,這意味着在iPhone桌面上的應用圖標在收到通知時,右上角圓點內所展示的數字就是badge的值。

這個屬性值是applicationIconBadgeNumber,它是UIApplication的屬性,設置為0即為隱藏,默認也是0。

UIApplication.shared.applicationIconBadgeNumber = 0

消息推送回調代理

接收用戶對消息推送的反饋事件,比如說應用在後台收到了通知,用戶點擊了這條通知進入到了APP裏面,我們需要獲取這個事件去做一些處理,比如跳去某個界面,這裡例子不講這麼複雜,只通過簡單地判斷用戶是通過哪個通知進來的。

接收回調代理事件前,需要遵循UNUserNotificationCenterDelegate協議,並設置delegate接收的對象。

extension AppDelegate: UNUserNotificationCenterDelegate {}

UNUserNotificationCenter.current().delegate = self

Swift語言中,可以通過extension擴展類遵循的協議,並在extension

當應用在前台運行時,收到的是這個-userNotificationCenter:willPresentNotification:withCompletionHandler:代理方法。UNNotification對象存儲了傳遞到應用的一些數據,通過此對象可以拿到此條通知關聯的觸發器notification.request.trigger,從而判斷其類型。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    guard let trigger = notification.request.trigger else { return; }
    if trigger.isKind(of: UNTimeIntervalNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNTimeIntervalNotificationTrigger")
    } else if trigger.isKind(of: UNCalendarNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNCalendarNotificationTrigger")
    }
}

當應用在後台,或者被殺死的狀態下,收到的是這個-userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:代理方法。此方法接收UNNotificationResponse類型的參數,它裏面包含notification屬性,因此可以參考上面的代碼進行觸發器的判斷。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    guard let trigger = response.notification.request.trigger else { return; }
    if trigger.isKind(of: UNTimeIntervalNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNTimeIntervalNotificationTrigger")
    } else if trigger.isKind(of: UNCalendarNotificationTrigger.classForCoder()) {
        print("Notification did receive, Is class UNCalendarNotificationTrigger")
    }
}

總結

  1. 本地通知有三種類型的觸發器,分別是UNTimeIntervalNotificationTrigger、UNCalendarNotificationTrigger和UNLocationNotificationTrigger。
  2. UNTimeIntervalNotificationTrigger在設置循環通知時,所設定的時間隔不能低於60秒,否則會報運行時錯誤。

往期回顧

  1. SwiftUI – 一起來仿寫微信APP之一首頁列表視圖
  2. SwiftUI – 一步一步教你使用UIViewRepresentable封裝網絡加載視圖(UIActivityIndicatorView)

Demo 源碼下載

我已經把 Demo 上傳至 GitHub 上面,項目名字是 SwiftUI-Tutorials,目錄名為GCLocalUserNotification,有需要的朋友可以去下載運行一下,當然你也可以跟着文章去做一遍,這樣更有利於你掌握此方面的知識。

如果本文章對你有幫助,請關注我,你的關注就是我後續寫文章的動力,下期會更精彩噢!

關於作者

博文作者:GarveyCalvin

微博://weibo.com/feiyueharia

博客園://www.cnblogs.com/GarveyCalvin

本文版權歸作者,歡迎轉載,但必須保留此段聲明,並給出原文鏈接,謝謝合作!

公眾號

作者第一次運營公眾號,請你們一定要關注我的公眾號,給我點動力,後期主要運營公眾號為主。這是第三篇發佈的文章,需要你們的支持,謝謝你們!

微信群

佛系等待你們的到來,若二維碼過期,請加我QQ:1147626297,記得寫備註,我重新發鏈接給你。快來加入我的「億」個人群吧!