面试题答案
一键面试关键步骤
- 导入框架:在Swift文件开头导入
UserNotifications
框架。
import UserNotifications
- 配置权限:向用户请求推送通知权限。
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("Notification permissions granted.")
} else if let error = error {
print("Error requesting authorization: \(error)")
}
}
- 创建通知内容:设置通知的标题、副标题、正文等。
let content = UNMutableNotificationContent()
content.title = "间隔触发通知"
content.subtitle = "这是一个基于时间间隔触发的通知"
content.body = "点击通知跳转到特定视图控制器"
content.sound = UNNotificationSound.default
- 设置触发条件:基于时间间隔设置触发。
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: true) // 每小时触发一次
- 创建通知请求:将通知内容和触发条件组合成通知请求。
let request = UNNotificationRequest(identifier: "intervalNotification", content: content, trigger: trigger)
- 添加通知请求到通知中心:
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Error adding request: \(error)")
}
}
代理方法
实现UNUserNotificationCenterDelegate
协议,用于处理用户点击通知的操作。
- 设置代理:在
AppDelegate
的application(_:didFinishLaunchingWithOptions:)
方法中设置代理。
UNUserNotificationCenter.current().delegate = self
- 实现代理方法:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 获取当前视图控制器栈
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let rootViewController = windowScene.windows.first?.rootViewController else {
completionHandler()
return
}
// 这里假设要跳转到的视图控制器是`TargetViewController`
let targetViewController = TargetViewController()
var viewController = rootViewController
while let presentedViewController = viewController.presentedViewController {
viewController = presentedViewController
}
viewController.present(targetViewController, animated: true, completion: nil)
completionHandler()
}
}
配置相关权限
-
在
Info.plist
文件中添加权限描述:NSUserNotificationUsageDescription
:描述应用为何要使用推送通知。例如:$(PRODUCT_NAME)的通知可以让您接收关于新消息、提醒等的信息。
-
在
Capabilities
中开启Push Notifications
:在项目设置中,选择Capabilities
标签,开启Push Notifications
。这一步会自动在项目中添加相关的Entitlements文件配置推送通知权限。