面试题答案
一键面试- 引入头文件:
import UserNotifications
- 创建本地通知的基本代码结构如下:
// 请求授权 UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (granted, error) in if granted { print("Notification authorization granted.") } else if let error = error { print("Error requesting authorization: \(error)") } } // 创建通知内容 let content = UNMutableNotificationContent() content.title = "通知标题" content.subtitle = "通知副标题" content.body = "通知正文内容" // 创建触发条件,这里以立即触发为例 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) // 创建通知请求 let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger) // 添加通知请求到通知中心 UNUserNotificationCenter.current().add(request) { (error) in if let error = error { print("Error adding notification: \(error)") } }
上述代码首先引入UserNotifications
框架,然后请求通知授权,接着创建通知内容,设置标题、副标题和正文,定义触发条件,创建通知请求,最后将通知请求添加到通知中心。这里设置的是5秒后立即触发通知,且不重复触发。