2016-11-23 56 views
2

當我發送推送通知時,應用程序在前臺willPresent被調用。 didReceive永遠不會被調用。當應用程序在後臺,並且收到推送通知時,會顯示警報,但應用程序不會調用didReceivewillPresentUNUserNotificationCenter didReceive未被調用

在項目>功能中,我檢查了背景模式Location updatesRemote notifications。位置更新是針對不相關的代碼。

我也啓用了推送通知。這是工作正常,因爲他們正在接受。

我已經實現了UNUserNotificationCenter通知東西在我的AppDelegate,見下圖:

import UserNotifications 
... 

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 
... 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     ... 
     registerForPushNotifications(application: application) 
     ... 
    } 

    // MARK: - Push Notifications 

    func registerForPushNotifications(application: UIApplication) { 
     let notificationCenter = UNUserNotificationCenter.current() 
     notificationCenter.delegate = self 
     notificationCenter.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in 
      if (granted) 
      { 
       UIApplication.shared.registerForRemoteNotifications() 
      } 
      else{ 
       //Do stuff if unsuccessful... 
       print("Unsuccessful in registering for push notifications") 
      } 
     }) 
    } 

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
     //convert the deviceToken to a string 
     let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined() 

     let ud = UserDefaults.standard 
     ud.set(deviceTokenString, forKey: "deviceToken") 
    } 

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
     //Handle the notification 
     print("User Info = ",notification.request.content.userInfo) 
     completionHandler([.alert, .badge, .sound]) 
    } 

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     //handle the notification 
     print("Push notification: ",response.notification.request.content.userInfo) 

     ... code to import the notification data into Core Data. 

     completionHandler() 
    } 

... 
} 

任何想法,爲什麼didReceive不會被調用?

這是收到推送通知:

[AnyHashable("aps"): { 
    alert = "[name] has added you as a friend."; 
    category = "NEWS_CATEGORY"; 
    "related_user_id" = 55; 
    sound = default; 
    type = "friend_request"; 
}] 

iOS的10.1,斯威夫特3

+0

你在波紋管IOS 10.0的測試被稱爲(推送通知,可向下滑動,等等)? –

+0

@jigneshVadadoriya不,ios 10.1 – toast

回答

0

如果您在通知旗幟挖掘的willPresent方法將被調用。

如果您希望在後臺處理推送通知而無需點擊橫幅,那麼您應該在通知負載中附加{「content-available」:1}。這種類型的推送通知被稱爲無聲推送。這將而不是創建一個通常的推送通知橫幅/警報,你將不得不自己創建橫幅。

當您收到帶有「content-available」的推送通知時,將在應用程序位於後臺時調用didReceive委託方法。

N.B.您還必須在plist文件的UIBackgroundModes密鑰中添加「遠程通知」。