2016-05-31 59 views
0

我可以在這個方法得到推送通知消息:顯示通知提醒當應用程序在前臺

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
} 

但問題是如何顯示,當應用程序被乳寧爲相同的方法,警報通知它當應用程序在後臺時顯示。

這可能嗎?

回答

1

didReceiveRemoteNotification將觸發不管你在遠近景或雖然,你可以seperately處理它們如下

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { 
     let state = UIApplication.sharedApplication().applicationState 
     if state == UIApplicationState.Active { 
      //show alert here your app is in foreground 
     } 
     else{ 
      //your app is in background 
     } 

    } 
+0

是啊,我知道,但我想顯示當應用程序在後臺顯示相同的警報通知 –

+0

好友,當應用程序在後臺,仍然活動,你可以創建一個本地通知,並把它扔掉:)它看起來絕對像遠程通知,你甚至可以處理徽章計數以及:)但當用戶點擊s的通知你將得到控制在didRecieveLocalNotification方法,這是所有:) –

+0

我已經做到了,我沒有得到橫幅警報,它只是顯示在通知中心沒有任何聲音或警報 –

2

當在前臺應用程序,你只能得到回調,iOS不顯示警報在這種情況下,你必須自己做...

你可以這樣說:

爲「PN前景視圖」創建一個筆尖,例如:

enter image description here

而當你在前臺得到一個PN,你可以實例化視圖,並將其與動畫添加到一個UIWindow,代碼例如:

 // init and configure your custom PN foreground view 
     let nib = UINib(nibName: self.nibName, bundle: NSBundle(forClass: PnForegroundView)) 
     pnForegroundView = nib.instantiateWithOwner(nil, options: nil)[0] as! PnForegroundView 
     pnForegroundView.setWidth(UIScreen.width) 
     pnForegroundView.setHeight(63) 
     pnForegroundView.title = <some title from notification> 
     pnForegroundView.image = <some image from notification> 

     // add the view to the key window 
     let window = UIApplication.sharedApplication().keyWindow! 
     window.addSubview(pnForegroundView!) 

     // Change window level to hide the status bar 
     window.windowLevel = UIWindowLevelStatusBar 

     // Show the PN foreground view with animation: 

     self.pnForegroundView!.setBottom(0) 
     self.changeWindowLevelToHideStatusBar() 
     UIView.animateWithDuration(0.2) { 
      self.pnForegroundView!.setBottom(self.pnForegroundView!.height) 
     } 

當然,你應該設定一個代表對於這個視圖,用戶點擊通知的情況以及用戶解除它的情況。

此外,您可以添加時間自動解僱。

最後一件事 - 取出PnForegroundView時,你最好重置UIWindow級別設置爲默認值,顯示在狀態欄

2

並稱completionHandler線的appDelegate方法爲我工作:

//Called when a notification is delivered to a foreground app. 
@available(iOS 10.0, *) 
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
print("User Info = ",notification.request.content.userInfo) 

completionHandler([.alert, .badge, .sound]) 
} 
相關問題