锁定屏幕上的本地通知ios

时间:2018-04-11 10:46:41

标签: ios swift notifications localnotification

我希望在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 

请建议,我错过了什么。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

您的代码有效,您必须增加时间间隔,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)

答案 1 :(得分:0)

您可以使用共享的UNUserNotificationCenter对象来安排本地通知。 您需要将Usernotifications框架导入swift文件,然后您可以请求本地通知。

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")
                    }
                })