我正在使用 Swift 3 进行编码,我只是想立即发送通知,没有任何延迟或间隔。但是,通知永远不会被触发。这是我的代码..
ViewController 代码
import UserNotifications
class HomeViewController: UIViewController{
var isGrantedNotificationAccess:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge],
completionHandler: { (granted,error) in
self.isGrantedNotificationAccess = granted
})
if isGrantedNotificationAccess{
triggerNotification()
}
}
//triggerNotification func goes here
}
触发通知函数:
func triggerNotification(){
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Notification Testing", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "This is a test", arguments: nil)
content.sound = UNNotificationSound.default()
content.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber;
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 1.0,
repeats: false)
let request = UNNotificationRequest.init(identifier: "testTriggerNotif", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
}
我做错了什么?
最佳答案
您缺少处理,当应用程序处于前台时,您没有指定通知的外观或呈现方式。
在添加通知时设置下行以指定您希望在用户使用应用程序时显示横幅(iOS 10 新功能)。
在构造您的 UNMutableNotificationContent
对象时添加以下代码行:
content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
您还应该在 AppDelegate 中添加以下方法:
// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNNotificationPresentationOptions.alert)
}
关于ios - Swift - 本地通知不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373321/