我想在iOS中锁定屏幕时发送本地通知。下面是我添加的代码。但在屏幕锁定时无法收到通知
let notification = UILocalNotification()
notification.alertAction = "Go back to App"
notification.alertBody = "Phone Found..!!"
notification.fireDate = NSDate(timeIntervalSinceNow: 1) as Date
UIApplication.shared.scheduleLocalNotification(notification)
notification.soundName = UILocalNotificationDefaultSoundName
请建议,我错过了什么。提前谢谢你。
你的代码工作把你必须增加时间间隔,UILocalNotification
被弃用UNUserNotificationCenter
UNUserNotificationCenter.current().requestAuthorization(options: [.alert])
{ (success, error) in
if success {
print("Permission Granted")
} else {
print("There was a problem!")
}
}
let notification = UNMutableNotificationContent()
notification.title = "title"
notification.subtitle = "subtitle"
notification.body = "the body."
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
可以使用共享的 UNUserNotificationCenter 对象来计划本地通知。您需要将用户通知框架导入到 swift 文件中,然后您可以请求本地通知。
import UserNotifications
你需要在AppDelegate的didFinishLaunchingWithOptions中调用该函数。
registerForLocalNotifications()
注册本地通知((的定义
func registerForLocalNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: (granted)")
guard granted else {return}
self.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: (settings)")
guard settings.authorizationStatus == .authorized else {return}
// UIApplication.shared.registerForRemoteNotifications()
}
}
然后,您可以像这样创建通知内容和通知请求。
let content = UNMutableNotificationContent()
content.title = "Title of Notification"
content.body = "Body of Notification"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true)
let request = UNNotificationRequest(identifier: "Identifier of notification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
if let error = error {
print("SOMETHING WENT WRONG")
}
})