要在 Swift 中发送本地通知,您需要使用'UNUserNotificationCenter'类。下面是一个示例代码,可以设置通知的时间和内容:

import UIKit
import UserNotifications

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 请求用户授权
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            if granted {
                print('用户授权了通知')
            } else {
                print('用户拒绝了通知')
            }
        }
    }
    
    @IBAction func scheduleNotificationButtonTapped(_ sender: UIButton) {
        // 创建通知内容
        let content = UNMutableNotificationContent()
        content.title = '本地通知'
        content.body = '这是一条本地通知的内容'
        content.sound = UNNotificationSound.default
        
        // 创建通知触发器,设置触发时间
        let date = Date().addingTimeInterval(10)  // 10秒后触发通知
        let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
        
        // 创建通知请求
        let identifier = 'LocalNotification'
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        
        // 添加通知请求到通知中心
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print('添加通知请求失败:(error.localizedDescription)')
            } else {
                print('通知请求已添加到通知中心')
            }
        }
    }
}

在上述代码中,我们首先在'viewDidLoad'方法中请求用户授权,以便发送通知。然后,当用户点击“发送通知”按钮时,我们创建一个'UNMutableNotificationContent'对象,设置通知的标题、内容和声音。接下来,我们使用'UNCalendarNotificationTrigger'来设置通知的触发时间。在这个例子中,我们设置通知在当前时间的10秒后触发。

最后,我们创建一个'UNNotificationRequest'对象,将通知内容和触发器添加进去。然后,我们调用'UNUserNotificationCenter.current().add(request)'方法将通知请求添加到通知中心。

请注意,您还需要在项目的'Info.plist'文件中添加以下内容,以允许发送通知:

<key>NSMicrophoneUsageDescription</key>
<string>需要通知权限</string>
<key>NSLocalNetworkUsageDescription</key>
<string>需要通知权限</string>
<key>NSUserNotificationEnabled</key>
<string>YES</string>

希望这可以帮助到你!

Swift 本地通知教程:设置时间和内容

原文地址: https://www.cveoy.top/t/topic/qECa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录