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

6
我一直在寻找如何在特定时间发送通知的答案。我需要它在每个工作日早上8:00向用户设备显示本地通知。我知道这个问题以前被回答过。我找到了一个Stack Overflow问题:Local Notifications at a specific time
不幸的是,由于iOS 11的发布,大部分代码已从Swift中删除,因此它已经相当过时了。我需要一个更近期的答案。我对Swift编程还比较新手,如果有人能帮助我并给我一个最新的答案,那将是太棒了!
2个回答

1
这是我使用通知中心进行本地通知调度的示例。
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创建它。

在应用程序委托中启动时,您需要请求本地通知的权限以使其正常工作。以下是一个示例。

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")
            }
        }
    }
}

1

Swift 5

这是一个使用通知中心进行本地通知调度的示例。

import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    //MARK: Authorization
    let center = UNUserNotificationCenter.current()
    
    
    //Delegate for UNUserNotificationCenterDelegate
    center.delegate = self
    
    //Permission for request alert, soud and badge
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        // Enable or disable features based on authorization.
        if(!granted){
            print("not accept authorization")
        }else{
            print("accept authorization")
            
            center.delegate = self
            
            
        }
    }
    return true
}

}

发送通知。
let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "We have a new message for you", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Open the app for see", arguments: nil)
        content.sound = UNNotificationSound.default
        content.badge = 1
        let identifier = id.uuidString

    //Receive notification after 5 sec
    //let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //Receive with date
    var dateInfo = DateComponents()
    dateInfo.day = day //Put your day
    dateInfo.month = month //Put your month
    dateInfo.year = year // Put your year
    dateInfo.hour = 8 //Put your hour
    dateInfo.minute = 0 //Put your minutes
    
    //specify if repeats or no
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
    
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    let center = UNUserNotificationCenter.current()
    print(identifier)
    center.add(request) { (error) in
        if let error = error {
            print("Error \(error.localizedDescription)")
        }else{
            print("send!!")
        }
    }

记住在文档中阅读这个内容:

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/index.html#//apple_ref/doc/uid/TP40008194-CH3-SW1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接