我无法在设置的时间在xcode模拟器上显示本地通知

问题描述 投票:0回答:1

我对编码还很陌生,想知道如何执行此操作,或者我的代码是否有问题。我最初将其设置为在模拟器接受通知后十秒钟关闭,但实际的通知也不会在该位置关闭。

import UIKit
import UserNotifications

class ViewController: UIViewController {

  override func viewDidLoad() {
      super.viewDidLoad()

     // Do any additional setup after loading the view.
      let center = UNUserNotificationCenter.current()
      center.requestAuthorization(options: [.alert, .sound])
          { (granted, error) in

      }
      let content = UNMutableNotificationContent()
      content.title = "Prevent nosocomial infections!"
      content.body = "Make sure to do hand hygiene"
      content.sound = .default

      var dateComponents = DateComponents ()
      dateComponents.hour = 9
      dateComponents.minute = 30

      let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
      let uuidString = UUID().uuidString
      let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)

      center.add(request) { (error) in
      }
    }
}
ios swift xcode uilocalnotification simulator
1个回答
0
投票

我最初将其设置为在模拟器接受通知后十秒钟关闭

不,那不是你在做什么。 center.requestAuthorization异步返回其值。因此,您试图在用户已接受通知的情况下安排通知[[之前:对话框仍然打开,询问通知,与此同时,您直接继续执行代码。显然,这是行不通的,因为通知尚未被接受。您需要将该代码移至requestAuthorization的完成处理程序(当前为空)。

© www.soinside.com 2019 - 2024. All rights reserved.