You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在iOS应用设置中实现Direct Messages通知切换开关

iOS 18.1 「Direct Messages」通知开关配置与发送实现

一、让「Direct Messages」开关显示在「Always deliver immediately」区域

核心是通过通知类别配置标记即时投递属性,关联到应用通知设置:

  1. 注册带即时投递属性的通知类别
    在应用启动阶段(如AppDelegate的didFinishLaunchingWithOptions或SceneDelegate的sceneWillEnterForeground),创建并注册指定类别的通知,设置.immediateDelivery选项,同时配置本地化名称:
import UserNotifications

func setupNotificationCategories() {
    let directMessageCategory = UNNotificationCategory(
        identifier: "direct_message_category",
        actions: [],
        intentIdentifiers: [],
        options: [.immediateDelivery], // iOS 18+ 标记为即时投递类别
        displayName: NSLocalizedString("Direct Messages", comment: "私信通知分组")
    )
    
    UNUserNotificationCenter.current().setNotificationCategories([directMessageCategory])
}
  1. 配置应用类别(可选但推荐)
    在Info.plist中添加LSApplicationCategoryType键,值设为com.apple.category.social,让系统识别应用为社交类,适配高优先级私信场景:
<key>LSApplicationCategoryType</key>
<string>com.apple.category.social</string>
  1. 确保通知权限已授权
    向用户请求必要的通知权限(至少包含.alert或.provisional),无权限则系统不会显示通知设置选项:
func requestNotificationPermissions() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        if granted {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
}

注意:首次配置后,需发送至少一条对应类别的通知,系统才会在「Always deliver immediately」区域显示该开关。

二、发送「Direct Messages」类即时通知

发送时需关联已注册的类别标识符,并设置即时投递机制:

本地通知示例

func sendDirectMessageNotification() {
    let content = UNMutableNotificationContent()
    content.title = "新私信"
    content.body = "你收到了一条来自张三的私信"
    content.categoryIdentifier = "direct_message_category" // 关联注册的类别
    content.deliveryMechanism = .immediate // iOS 18+ 指定即时投递
    content.interruptionLevel = .timeSensitive // 确保通知及时触达
    
    // 时间触发器仅作测试,实际可替换为远程通知或其他触发器
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, 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)")
        }
    }
}

远程推送Payload示例

{
    "aps": {
        "alert": {
            "title": "新私信",
            "body": "你收到了一条新私信"
        },
        "category": "direct_message_category",
        "delivery-mechanism": "immediate",
        "interruption-level": "time-sensitive"
    }
}

内容的提问来源于stack exchange,提问作者KubikJAW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:10:10