所以我一直在尝试向新的UNUserNotificationCenter添加通知,但我似乎没有得到它 .
我的视图控制器有一个动作:
@IBAction func sendPressed(_ sender: AnyObject) {
let content = UNMutableNotificationContent()
content.title = "Hello"
content.body = "What up?"
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
print(error)
}
print("should have been added")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let center = UNUserNotificationCenter.current()
center.requestAuthorization([.alert, .sound]) { (granted, error) in
}
}
我在项目中也有一个 Notification Content Extension
,但它似乎根本没有被触发,任何想法我从用户文档中尝试了这个例子,但它并没有告诉我更多或者我错过了它 .
这里:https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent
另外:https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications
编辑:
所以把应用程序放在后台就可以了 .
5 回答
你需要注册通知...我试过,这是有效的 .
Edit: 您不需要将您的应用程序置于后台,以便从iOS 10开始提供通知 .
使用下面的回调配置通知以显示在前台 .
Here是一个示例项目 .
使用Objective-C实现:
我在这里写了一个Demo项目:iOS10AdaptationTips .
请求授权:
安排localNotification
更新应用程序图标徽章编号
然后它会显示如下:
在后台:
锁屏:
如果默认重复只显示一个
而不是在iOS9的锁定屏幕上显示多个:http://i67.tinypic.com/98t75s.jpg并且还自动支持3D Touch http://a67.tinypic.com/dorw3b.jpg
我在这里写了一个Demo:iOS10AdaptationTips .
以下是几个步骤:
确保您拥有 permission . 如果没有,请使用UNUserNotificationCenter.current() . requestAuthorization来获取它 . 如果您想多次显示请求,请按照answer进行操作 .
如果要显示通知 foreground ,必须将UNUserNotificationCenterDelegate分配给某个地方 .
给我看看代码
I solved my problem as follows (Firebase, Swift 3):
如果未将演示文稿选项传递给completionHandler方法,则不会触发通知 .
我已经为Swift 3做了一个可能有帮助的实现,你可以在这里查看:https://stackoverflow.com/a/45381380/2296630