gpt4 book ai didi

swift - 经过一定时间后触发 Xcode 通知(Swift 3)

转载 作者:可可西里 更新时间:2023-11-01 00:35:48 25 4
gpt4 key购买 nike

我已经尝试了很多东西,但我似乎无法弄清楚在(示例)2 天或 5 小时内使用哪个命令来触发警报。谁能帮我吗?我希望能够执行以下操作:

var number = 3
var repeat = day
*Code with 'number' and 'repeat' in it.*

所以在这种情况下,它会在 3 天内发出警报。这里有人知道该怎么做吗? ^^

提前致谢!

最佳答案

首先,将其放在需要通知的文件顶部:

import UserNotifications

然后把这个放在 AppDelegateapplication(_:didFinishLaunchingWithOptions:)

let notifCenter = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound]
notifCenter.requestAuthorization(options: options, completionHandler: nil)

所以现在请求通知如下:

// timeInterval is in seconds, so 60*60*12*3 = 3 days, set repeats to true if you want to repeat the trigger
let requestTrigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*60*12*3), repeats: false)

let requestContent = UNMutableNotificationContent()
requestContent.title = "Title" // insert your title
requestContent.subtitle = "Subtitle" // insert your subtitle
requestContent.body = "A body in notification." // insert your body
requestContent.badge = 1 // the number that appears next to your app
requestContent.sound = UNNotificationSound.default()

// Request the notification
let request = UNNotificationRequest(identifier: "PutANameForTheNotificationHere", content: requestContent, trigger: requestTrigger)

// Post the notification!
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
// do something to the error
} else {
// posted successfully, do something like tell the user that notification was posted
}
}

这部分代码做了三件事:

  1. 定义触发器
  2. 创建通知上下文
  3. 发布上下文

如果您打算继续使用通知,请查看 this tutorial ,其中还讨论了当用户点击您的通知时如何使用react。


注意:UNMutableNotificationContext 是可变的,与名称无关,UN 只是命名空间。不要混淆!


Notification

如果您提供副标题,它将位于标题和正文之间。


这是 badge 属性:

enter image description here

关于swift - 经过一定时间后触发 Xcode 通知(Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42993882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com