Din*_*uka 2 xcode notifications ios uilocalnotification 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
}
Run Code Online (Sandbox Code Playgroud)
triggerNotification函数:
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)
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您错过了处理,当应用程序处于前台时,您没有指定通知的外观或显示方式
在添加通知时设置在行下方,以指定您在用户使用应用时显示横幅(iOS 10新功能)
content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
Run Code Online (Sandbox Code Playgroud)
//更新的triggerNotification
// 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)
}
Run Code Online (Sandbox Code Playgroud)
在AppDelegate中添加以下方法
content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2626 次 |
| 最近记录: |