User Notifications — UNMutableNotificationContent

UNMutableNotificationContent

This article is extracted from the chat log with AI. Please identify it with caution.

UNMutableNotificationContent 是 iOS/macOS 开发中用于配置本地通知内容的类,属于 UserNotifications 框架。它允许开发者动态设置通知的标题、内容、声音、附加数据等属性。以下将分场景和用法详细说明:


一、使用场景 #

  1. 动态内容通知
    当通知内容需根据用户行为或应用数据实时生成时使用,例如:

    • 社交媒体应用:显示不同发送者名称和消息预览
    • 待办事项应用:动态展示任务名称和截止时间
  2. 交互式通知
    需要添加自定义操作按钮(如回复、点赞)时,需配合 UNNotificationCategory 使用。

  3. 多媒体通知
    需在通知中显示图片、音频或视频时,通过 attachments 属性添加。

  4. 本地化通知
    动态替换本地化字符串,如根据用户语言设置显示不同内容。


二、使用方法 #

1. 基本配置 #

import UserNotifications

// 创建实例
let content = UNMutableNotificationContent()
content.title = "新消息提醒" // 主标题
content.subtitle = "来自好友" // 副标题
content.body = "您收到一条新消息:点击查看详情" // 正文内容
content.badge = 1 // 应用角标数字
content.sound = UNNotificationSound.default // 默认提示音

2. 添加用户数据 #

// 携带自定义数据(点击通知时可通过userInfo获取)
content.userInfo = [
    "message_id": "12345",
    "sender": "User123"
]

3. 多媒体附件 #

// 添加图片附件(需处理错误)
if let url = Bundle.main.url(forResource: "cat", withExtension: "jpg") {
    do {
        let attachment = try UNNotificationAttachment(
            identifier: "image",
            url: url,
            options: nil
        )
        content.attachments = [attachment]
    } catch {
        print("附件加载失败: \(error)")
    }
}

4. 交互式通知 #

// 配置分类标识符(需提前注册Category)
content.categoryIdentifier = "MESSAGE_CATEGORY"

// 注册Category(通常在App启动时配置)
let replyAction = UNTextInputNotificationAction(
    identifier: "REPLY_ACTION",
    title: "快速回复",
    options: []
)
let category = UNNotificationCategory(
    identifier: "MESSAGE_CATEGORY",
    actions: [replyAction],
    intentIdentifiers: [],
    options: []
)
UNUserNotificationCenter.current().setNotificationCategories([category])

5. 发送通知 #

// 创建触发条件(5秒后触发)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

// 创建请求(需唯一标识符)
let request = UNNotificationRequest(
    identifier: UUID().uuidString,
    content: content,
    trigger: trigger
)

// 添加通知请求
UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print("通知发送失败: \(error.localizedDescription)")
    }
}

三、注意事项 #

  1. 权限请求
    首次使用需请求用户授权:

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in
        guard granted else { return }
        // 权限已获取
    }
    
  2. 线程安全
    所有操作应在主线程执行,避免UI相关错误。

  3. 附件限制

    • 图片尺寸不超过 10MB
    • 音频/视频不超过 5MB
    • 文件格式需符合系统要求
  4. 本地化技巧
    使用本地化字符串:

    content.title = NSString.localizedUserNotificationString(
        forKey: "NEW_MESSAGE_TITLE",
        arguments: nil
    )
    

四、完整示例 #

// 配置通知内容
let content = UNMutableNotificationContent().configure {
    $0.title = "待办事项提醒"
    $0.body = "您的会议将在15分钟后开始"
    $0.sound = .default
    $0.userInfo = ["meetingID": "A1234"]
    $0.categoryIdentifier = "EVENT_REMINDER"
}

// 设置触发时间(下一小时整点)
let date = Calendar.current.date(byAdding: .hour, value: 1, to: Date())!
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

// 发送通知
UNUserNotificationCenter.current().add(
    UNNotificationRequest(
        identifier: "MEETING_REMINDER",
        content: content,
        trigger: trigger
    )
)

通过灵活使用这些方法,您可以创建高度定制化的通知体验。建议测试时使用模拟器的「Debug」→「Simulate Notification」功能快速验证通知样式。

本文共 1005 字,创建于 May 28, 2025
相关标签: Xcode, SwiftUI, ByAI