我可以通过此方法获取推送通知消息:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
}
但问题是如何在应用程序运行时显示警报通知,就像应用程序处于后台时显示的那样。
这可能吗?
答案 0 :(得分:2)
当应用程序处于前台时,您只能获得回调,iOS在这种情况下不显示警报,您必须自己执行...
你可以这样做:
为“PN前景视图”创建一个笔尖,例如:
当您在前台获得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
级别重置为默认值,以显示状态栏
答案 1 :(得分: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])
}
答案 2 :(得分:1)
didReceiveRemoteNotification将触发,无论您是前景还是后台,但是,您可以单独处理它们,如下所示
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
}
}