ios - 如何在 Swift 中的特定时间发送本地通知?

标签 ios swift xcode uilocalnotification

我一直在寻找有关如何在一天中的特定时间发送通知的答案。我需要它在每个工作日的上午 8:00 向用户的设备显示本地通知。我知道这个问题之前已经回答过。我发现了一个 Stack Overflow 问题:Local Notifications at a specific time

不幸的是,它已经过时了,因为自 iOS 11 发布以来,大部分代码都从 Swift 中删除了。我需要一个更新的答案。我是 Swift 编程的新手。如果有人可以帮助我并给我一个更新的答案,那就太棒了!

最佳答案

这是我使用通知中心安排本地通知的示例。

let center = UNUserNotificationCenter.current()

let content = UNMutableNotificationContent()
content.title = "My title"
content.body = "Lots of text"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "yourIdentifier"
content.userInfo = ["example": "information"] // You can retrieve this when displaying notification

// Setup trigger time          
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
let testDate = Date() + 5 // Set this to whatever date you need
let trigger = UNCalendarNotificationTrigger(dateMatching: testDate, repeats: false)

// Create request               
let uniqueID = UUID().uuidString // Keep a record of this if necessary
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
center.add(request) // Add the notification request

Date 对象(由上面的 testDate 表示)可以是您想要的任何日期。从 DateComponents 创建它通常很方便。

您需要在启动时在 App Delegate 中请求本地通知的权限才能使其正常工作。这是一个例子。

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Ask permission for notifications
        let center = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("Permission granted")
            } else {
                print("Permission denied\n")
            }
        }
    }
}

关于ios - 如何在 Swift 中的特定时间发送本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009454/

相关文章:

android - 修复了 jQuery Mobile 中的标题滚动/拖动

android - 使用社交媒体身份验证的用户的 Firebase 重置密码问题

ios - 使用 WantsFullScreenLayout 应用程序处理扩展高度状态栏的最佳实践?

ios - 保存一个UIImage并在UIImageview上重用

iphone - TableViewSuite App 需要什么样的项目类型

ios - 在应用程序中本地存储大量图像的正确方法

swift - 无法在 Swift 中从该设备复制符号

Swift 4 Firebase 在 TableView 上显示用户组

ios - 在 SpriteKit 中将动态物理对象保持在手指下

ios - 是否允许让备用应用程序图标是动态的?