[英]Push notifications and token device in Swift
我正在開發一個需要知道設備令牌的應用程序,以便在用戶授權時向用戶發送通知。 系統第一次要求授權進行通知。 如果用戶說“允許”,則系統會要求我使用方法didRegisterForRemoteNotificationsWithDeviceToken,並且在此方法的主體中,我會在UserDefaults中寫入設備令牌。 這是流程:1)系統請求權限2)在didFinishLaunchingWithOptions中(在AppDelegate內部)我在管理Notification Framework的類中調用此方法:
func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("NFM permission granted: \(granted)")
// 1. Check if permission granted
guard granted else { return }
// 2. Attempt registration for remote notifications on the main thread
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
3)系統為我調用了didRegisterForRemoteNotificationsWithDeviceToken方法(在AppDelegate中),並且一切正常。 在方法的主體中,編寫令牌UserDefaults設置。 第二種情況是用戶第一次拒絕該權限。 在第二種情況下,在我的應用程序的另一個ViewController中,我檢查用戶是否已使用設備設置授予了推送通知的權限(因此不在應用程序中)。 在我的應用程序的特定部分,我使用此方法來驗證用戶是否已獲得授權(該類始終在我的類中管理Notification Framework)。
func checkPremissionStatus() -> Bool{
var isAuth = false
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("NFM checkPremissionStatus -> notification status")
switch settings.authorizationStatus {
case .authorized:
print("NFM checkPremissionStatus -> authorized status")
self.autorizzato = true
isAuth = true
//TODO check pending notification...
case .denied:
print("NFM checkPremissionStatus -> denied status")
self.autorizzato = false
isAuth = false
case .notDetermined:
print("NFM notDetermined never see this print")
}
}
return isAuth
}
在此特定情況下,不會調用方法didRegisterForRemoteNotificationsWithDeviceToken,因此無法存儲令牌。 向用戶詢問授權的警報僅在用戶第一次使用時打開該應用。 下次用戶打開應用程序時,系統不再顯示警報。 我怎么解決這個問題?
謝謝。
我以這種方式解決了這個問題:在方法checkPremissionStatus中,我對方法registerForPushNotifications添加了一個調用,並以此方式系統調用了didRegisterForRemoteNotificationsWithDeviceToken方法,因此我可以在應用程序的業務邏輯中使用設備令牌。 這是在管理Notification Framework的類中修改的代碼。
func checkPremissionStatus() -> Bool{
var isAuth = false
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("NFM checkPremissionStatus -> notification status")
switch settings.authorizationStatus {
case .authorized:
print("NFM checkPremissionStatus -> authorized status")
self.autorizzato = true
isAuth = true
print("NFM checkPremissionStatus -> call registerForPushNotification")
self.registerForPushNotifications()
//TODO check pending notification...
case .denied:
print("NFM checkPremissionStatus -> denied status")
self.autorizzato = false
isAuth = false
case .notDetermined:
print("NFM notDetermined never see this print")
}
}
return isAuth
}
因此,當我檢查用戶權限時,我發現用戶已啟用(從設備設置中)推送通知用例。授權系統調用正確的方法,並且可以將設備令牌存儲在用戶首選項中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.