【问题标题】:SWIFT send local notificationSWIFT 发送本地通知
【发布时间】:2018-06-28 10:12:57
【问题描述】:

我正在尝试按照本教程发送本地通知: https://useyourloaf.com/blog/local-notifications-with-ios-10/

我将此代码添加到我的viewDidLoad()

    let center = UNUserNotificationCenter.current()
    let options: UNAuthorizationOptions = [.alert, .sound];
    center.requestAuthorization(options: options) {
        (granted, error) in
        if !granted {
            print("Something went wrong")
        }
    }
    let content = UNMutableNotificationContent()
    content.title = "Don't forget"
    content.body = "Buy some milk"
    content.sound = UNNotificationSound.default()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5,
                                                    repeats: false)

    let identifier = "UYLLocalNotification"
    let request = UNNotificationRequest(identifier: identifier,
                                        content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            print("error")
        }
    })

但是 5 秒过去了,没有显示任何通知。 CompletionHandler 被调用,errornil

【问题讨论】:

  • 当它应该触发时,你的应用是在前台还是后台?检查stackoverflow.com/questions/49902505/… ?
  • 两种情况我都想要
  • 在后台应该是正常的。在前台,您需要点击链接。此外,为了进行更好的测试,请至少在 30 秒内启动它。
  • 好的,我刚刚注意到它在应用程序处于后台时确实有效。至于链接,我不明白他们的建议,我不熟悉objective-c

标签: swift


【解决方案1】:

如果您想在应用程序处于前台时收到通知,那么您必须在控制器中添加更多代码,

  • viewDidLoad()末尾添加下面一行

    center.delegate = self

    这使您的 ViewController 成为通知命中时可以回调的委托。

  • 向委托确认您的视图控制器,(添加UNUserNotificationCenterDelegate

    class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    现在您可以在 ViewController 中编写回调方法了。

  • 编写回调来显示你的通知,你可以在viewDidLoad()之后添加这个方法

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) }

    即使应用程序在前台,这也会让您的通知弹出。

注意:强烈建议您在 AppDelegate 而不是 ViewController 中注册通知(本地/远程)。

【讨论】:

  • 谢谢,它成功了。只是为了我的理解:我不明白为什么这个 func 有任何效果,谁调用它?
  • 如果应用程序在前台,通知的默认行为是忽略它。因为预计如果需要,开发人员将提供在前台收到通知时要执行的操作。一些开发人员希望显示时尚的警报或希望执行某些操作。无论您是否调用completionHandler,应用程序都会处理您需要显示横幅的.alert.badge 来更新徽章数量(如果有)以及.sound 来播放声音。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多