2017-07-18 57 views
0

我試着寫一個函數來檢查我是否已達到64個本地通知的限制。有一些解決方案來處理UIlocalNotifications,但我還沒有找到一個NSlocalNotifications。這裏是我的功能計數掛起本地通知

 func notificationLimitreached() { 
    let center = UNUserNotificationCenter.current() 
    var limit = false 
    center.getPendingNotificationRequests(completionHandler: { requests in 
     print(requests.count) 
     if requests.count > 59 { 
      limit = true 
      print(limit) 
     } else { 
      limit = false 
     } 

    }) 
    print (limit) 

問題是「限制」變量打印true閉包中時,然後離開關閉後重置爲假初始值。

其他我試過的東西。

- 設置全局變量時再次當我看到它的值內其他地方關閉其設定爲原始值

回答

3

正如你可以看到你所面對的異步邏輯:

您的打印功能首先爲false,因爲getPendingNotificationRequests關閉內有延遲。

試試這個功能,看看是否能工作:

func isNotificationLimitreached(completed: @escaping (Bool)-> Void = {_ in }) { 
    let center = UNUserNotificationCenter.current() 
    center.getPendingNotificationRequests(completionHandler: { requests in 

     completed(requests.count > 59) 
    }) 
} 

而且可以調用與下面的代碼此功能:

isNotificationLimitreached { isReached in 
     print(isReached) 
    } 
+0

upVoted,這是做到這一點的正確方法 –