0

當我第一次運行我的應用程序時,模擬器能夠顯示通知,而應用程序在前臺。`willPresent notification`不被調用&本地通知不會顯示當應用程序在iOS 10的前景

當我重新啓動該應用didReceive notification:(即從通知的iOS 9方法)被調用,而不是willPresent notification(即通知方法從iOS的10)和沒有任何通知被顯示而應用程序是在前臺。但是,如果應用程序在後臺,則會顯示通知。

這個question或這個question都不能解決這個問題。

我得到授權使用此代碼的通知:

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]? = [:]) -> Bool { 
       if #available(iOS 10.0, *) { 
        let center = UNUserNotificationCenter.current() 
        center.requestAuthorization(options: [.alert, .sound, .sound]) { (granted, error) in    
        UNUserNotificationCenter.current().delegate = self     
        }      
       } 
       return true 
      } 

而且我已經實現了willPresent通知方法:

@available(iOS 10.0, *) 
      func userNotificationCenter(_ center: UNUserNotificationCenter, 
             willPresent notification: UNNotification, 
             withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)      completionHandler(UNNotificationPresentationOptions.alert) 
      } 

下面是如何創建通知:

let content = UNMutableNotificationContent() 
     content.title = title 
     content.subtitle = subtitle 
     content.body = message 
     content.categoryIdentifier = identifier      

     let trigger = UNTimeIntervalNotificationTrigger(
      timeInterval: 10.0, 
      repeats: false) 

     let request = UNNotificationRequest(
      identifier: "identifier", 
      content: content, 
      trigger: trigger 
     ) 

     UNUserNotificationCenter.current().add(
      request, withCompletionHandler: nil) 

問題簡而言之:我應該如何確保應用程序能夠在應用程序第一次運行後在前臺顯示通知?

在此先感謝。

+0

這是因爲標識符對於所有通知都是相同的。確保爲不同的通知添加不同的標識符。另外,爲什麼你要求'.sound'兩次許可? – bhakti123

回答

1

嘗試在requestAuthorization完成塊之外設置代理。這可能比你想要的晚。

我這裏補充一個樣本項目:https://github.com/jerbeers/DemoLocalNotification

如果你建立並運行,點擊按鈕,你將3秒後看到當地的通知。如果你停下來,建立並再次運行,即使應用程序正在運行,我也會看到本地通知。

+0

感謝您的回覆。我嘗試在requestAuthorization完成塊之前和之後設置委託,但它沒有解決問題。你能建議任何其他解決方案嗎? –

+0

告訴我你正在採取的步驟。當你說「第一次運行」和「重新啓動」時,你在做什麼? – Jerry

+0

我的意思是第一次運行;我第一次「安裝」應用程序,我是用「重新啓動」來表示;當我在模擬器中通過Xcode重新加載應用程序後,它已被安裝。 –

相關問題