2017-02-24 68 views
2
let content = UNMutableNotificationContent() 
content.badge = 0 // your badge count 

此代碼是在applicationWillEnterForeground和目的是通過數設爲0文擦除徽​​章用戶再次進入該應用然而,已經證明完全無用的,因爲它不更新應用程序圖標上的徽章...的Xcode夫特3.0通知框架應用徽章不更新

我現在已經恢復到iOS 9的代碼,它的工作就像一個魅力。此外,它似乎是,使用新的框架,你必須真正發出通知要更新的徽章數量這實在是不切實際的..有人請糾正我,如果我錯了

此外:

let content = UNMutableNotificationContent() 
     TableViewController.numberBadges += 1 
     content.title = "Title" 
     content.body = "this is the body ..." 
     content.badge = TableViewController.numberBadges as NSNumber? 
     content.sound = UNNotificationSound.default() 

     let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) 
     let requestidentifier = "myNotification" 
     let request = UNNotificationRequest(identifier: requestidentifier, content: content, trigger: trigger) 

     UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in 
      // handle error if there is one 
      if((error) != nil){ 
       print("Error completing notification scheduling: \(error)") 
      }else{ 
       print("Added Notification request successfully with \(content.badge!) badges") 
      } 

     }) 

不更新徽章,所以給了什麼?

+0

你有沒有試過'[UIApplication sharedApplication] .applicationIconBadgeNumber = 0;'? – deadbeef

+1

對不起,我的意思是'UIApplication.shared.applicationIconBadgeNumber = 0' – deadbeef

+0

這就是我目前使用的,然而問題是,爲什麼新框架根本不工作?它確實發送通知絕對好,但慘不忍睹的徽章管理。這是一個錯誤還是我做錯了代碼? –

回答

1

我有同樣的問題,直到我將content.badge作爲非可選項。

1

在iOS 10和11上,通過安排UNNotificationRequest通知來清除徽章存在問題。該文檔說,將UNMutableNotificationContent對象的badge屬性設置爲0會在通知被觸發時擦除徽章,但這似乎不起作用。通過實驗,我發現了這兩個iOS版本中的這個bug的解決方法。

在iOS 10/Xcode 8上,如您所見,將該值設置爲0這不起作用 - 徽章將繼續顯示其當前值。我發現如果將它設置爲-1:

let content = UNMutableNotificationContent() 
content.badge = -1 

然後它會在觸發通知時擦除徽章。

在iOS 11/Xcode 9中,將badge屬性設置爲小於1的任何值都不會執行任何操作 - 徽章將繼續顯示其當前值。我發現,如果你的徽章設置爲0,也可以設置聲音屬性,如:

let content = UNMutableNotificationContent() 
content.badge = 0 
content.sound = UNNotificationSound.default() 

然後徽章將被刪除。在我的應用程序中,我請求了使用requestAuthorization方法的許可來顯示徽章,但我沒有請求播放聲音的權限,因此在觸發通知時實際上沒有播放聲音。 (如果您的應用程序確實請求許可播放聲音,並且在清除徽章時不想播放聲音,我不知道解決方法是什麼。)

更新:我也通過模擬器,iOS 11的解決方法也適用於iOS 10.

只要badge屬性設置爲正數,我還沒有任何其他問題(還!)安排更新徽章的通知。