2017-04-14 80 views
1

與SWIFT 3.1爲什麼我沒有收到我的iPhone的任何通知?

下面就Xcode8.3運行,這是我在AppDelegate.swift

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

    let center = UNUserNotificationCenter.current() 

    center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in 
     if granted { 
      print("OK!") 
     } 
     else { 
      print("No!") 
     } 
    }) 

    application.registerForRemoteNotifications() 

    return true 
} 


func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { 
    print("==== didReceiveRemoteNotification ====") 
    print(userInfo) 
} 

代碼我使用節點APNS推送通知我的應用程序,我可以從我的調試領域有消息在Xcode中。

==== didReceiveRemoteNotification ==== 
[AnyHashable("id"): 123, AnyHashable("aps"): { 
    alert = "Hello World \U270c"; 
    badge = 3; 
}] 

但是,我沒有收到我的iPhone上的任何通知。

難道我失去了一些東西?

+0

可能重複[蘋果推送通知不生產](http://stackoverflow.com/questions/15595720/apple-push-notification-not-working-in-production) – iphonic

+0

你不需要代碼將設備標識符上傳到您的服務位置? – Alistra

+1

也許是因爲你的應用程序是'foreground'?推僅表現如果是'off'或'background' – JuicyFruit

回答

1

,如果你要處理的通知,當你的應用程序被激活,你應該做這樣的事情,因爲推視圖不會出現

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { 
    if application.applicationState == .active { 
     //create custom view or something 
    } else { 
     //it was background/off 
    } 
} 

你可能也有興趣在創造新的建設模式,所以你的應用程序會一直等到它啓動,所以你可以在接收推送時調試你的應用程序行爲。 enter image description hereenter image description here

+0

我不明白你的意思是什麼:「你的應用會一直等到它啓動,所以你可以在接收推送時調試你的應用行爲」你能否詳細說明與「自動「 – Honey

+0

@Honey它會在您的設備上編譯您的應用程序,但不會自動啓動它,因此您可以通過它自己發送推送並自行打開,以查看與之相關的一些控制檯日誌。 – JuicyFruit

+0

我明白您的意思了...說等待可執行文件翻譯爲'等待你手動點擊應用程序'?錯誤的命名! – Honey

1

隨着iOS的10,你可以做以下看到推送通知時,應用程序是在前臺。你必須在AppDelegate中實現下面的函數。它的UNUserNotificationCenterDelegate的委託方法。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

遵循以下步驟:

  1. 進口UserNotifications在AppDelegate中延長UNUserNotificationCenterDelegate

enter image description here

  • 搭建UNUserNotificationCenter代表在didFinishLaunchingWithOptions
  • let center = UNUserNotificationCenter.current()
    center.delegate = self
  • 實現的AppDelegate意願本方法和調用與所述選項中完成處理程序。現在
  • func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
         completionHandler([.alert,.badge,.sound]) 
    }

    ,如果你得到一推,就可以看到該通知提醒,即使你的應用程序是在前臺。 More Info in Apple Doc