MST
星途 面试题库

面试题:Swift中UserNotifications的通知触发条件及处理

在Swift项目里,使用UserNotifications框架实现一个基于时间间隔触发的通知,并且当用户点击该通知时,能够跳转到应用内特定的视图控制器,说明实现过程中涉及到的关键步骤、代理方法以及如何配置相关权限。
24.8万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试

关键步骤

  1. 导入框架:在Swift文件开头导入UserNotifications框架。
import UserNotifications
  1. 配置权限:向用户请求推送通知权限。
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)")
    }
}
  1. 创建通知内容:设置通知的标题、副标题、正文等。
let content = UNMutableNotificationContent()
content.title = "间隔触发通知"
content.subtitle = "这是一个基于时间间隔触发的通知"
content.body = "点击通知跳转到特定视图控制器"
content.sound = UNNotificationSound.default
  1. 设置触发条件:基于时间间隔设置触发。
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: true) // 每小时触发一次
  1. 创建通知请求:将通知内容和触发条件组合成通知请求。
let request = UNNotificationRequest(identifier: "intervalNotification", content: content, trigger: trigger)
  1. 添加通知请求到通知中心
UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print("Error adding request: \(error)")
    }
}

代理方法

实现UNUserNotificationCenterDelegate协议,用于处理用户点击通知的操作。

  1. 设置代理:在AppDelegateapplication(_:didFinishLaunchingWithOptions:)方法中设置代理。
UNUserNotificationCenter.current().delegate = self
  1. 实现代理方法
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()
    }
}

配置相关权限

  1. Info.plist文件中添加权限描述

    • NSUserNotificationUsageDescription:描述应用为何要使用推送通知。例如:$(PRODUCT_NAME)的通知可以让您接收关于新消息、提醒等的信息。
  2. Capabilities中开启Push Notifications:在项目设置中,选择Capabilities标签,开启Push Notifications。这一步会自动在项目中添加相关的Entitlements文件配置推送通知权限。