我对编码相当陌生,想知道如何做到这一点或者我的代码是否有问题。我最初将其设置为在模拟器接受通知后十秒关闭,但实际通知也不会在那里关闭。
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
}
}
}
最佳答案
I initially had it set to go off ten seconds after notifications were accepted by the simulator
不,那不是你正在做的事情。 center.requestAuthorization
异步返回其值。因此,您尝试在用户接受通知之前安排通知:对话框仍处于打开状态,询问通知,同时您可以直接继续执行代码。显然这是行不通的,因为通知尚未被接受。您需要将该代码移至 requestAuthorization
的(当前为空)完成处理程序中。
关于ios - 我无法让本地通知在 xcode 模拟器上的设定时间显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919922/