MST

星途 面试题库

面试题:Swift中如何设置UserNotifications的基本通知内容

在Swift中,使用UserNotifications框架时,阐述如何创建一个简单的本地通知,包括设置通知的标题、副标题、正文内容,并且指出需要引入哪些必要的头文件以及基本的代码结构。
33.2万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试
  1. 引入头文件
    import UserNotifications
    
  2. 创建本地通知的基本代码结构如下
    // 请求授权
    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秒后立即触发通知,且不重复触发。