Я хочу отправить локальное уведомление, когда экран заблокирован в 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 для планирования локальных уведомлений. Вам нужно импортировать структуру Usernotifications в свой быстрый файл, а затем вы можете запросить локальное уведомление.
import UserNotifications
И вам нужно вызвать функцию в вашем AppDelegate didFinishLaunchingWithOptions
registerForLocalNotifications()
Определение для 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")
}
})
timeIntervalSinceNow: 1
, как вы можете запустить этот код и в течение одной секунды заблокировать устройство? попробуйте увеличить это, а затем попробуйте еще раз ... возможно, он запускается, когда приложение открыто