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

SwiftUI中如何使用Notification Content Extension显示自定义样式通知

问题描述

我正在按照苹果官方教程尝试实现带自定义样式的iOS通知,这需要创建Notification Content Extension。我对自定义iOS通知和通知扩展的概念比较陌生,不清楚如何在SwiftUI项目中显示或测试这类自定义通知,希望能得到帮助。目前我已通过以下代码成功实现默认通知功能,希望尽可能沿用该结构实现自定义通知:

func testNotification() { //called in .onAppear()
     let content = UNMutableNotificationContent()
     content.title = "AppName Tracking"  //replace this with custom notification
     content.subtitle = "Don't forget to track your health" //replace this with custom notification
     content.sound = UNNotificationSound.default

     // show this notification 10 seconds from call
     let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
     let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

     UNUserNotificationCenter.current().add(request)
}

补充:以下是我的AppDelegate及相关方法:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}

实现自定义通知的步骤

1. 创建Notification Content Extension

  • 打开Xcode,在项目中点击 File > New > Target
  • 选择Notification Content Extension,点击Next
  • 设置扩展名称(比如CustomNotificationExtension),语言选择Swift,点击Finish
  • 弹出激活扩展提示时选择Activate

2. 修改现有通知代码,添加匹配标识

在你已有的testNotification()方法中,给通知内容添加分类标识符,让系统能匹配到对应的扩展:

func testNotification() { //called in .onAppear()
     let content = UNMutableNotificationContent()
     content.title = "AppName Tracking"
     content.subtitle = "Don't forget to track your health"
     content.sound = UNNotificationSound.default
     // 添加分类标识,需和扩展配置一致
     content.categoryIdentifier = "CustomNotificationCategory"

     let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
     let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

     UNUserNotificationCenter.current().add(request)
}

3. 配置扩展的Info.plist

打开扩展目标的Info.plist,确保以下配置正确:

  • NSExtension > NSExtensionAttributes > UNNotificationExtensionCategory 设为CustomNotificationCategory(和上面的标识一致)
  • NSExtension > NSExtensionAttributes > UNNotificationExtensionDefaultContentHidden 设为NO(保留默认标题副标题;设为YES则完全用自定义UI替换)
  • NSExtension > NSExtensionAttributes > UNNotificationExtensionInitialContentSizeRatio 设为1.0(控制自定义内容的高度比例)

4. 用SwiftUI构建自定义通知界面

默认扩展是UIKit实现,我们可以改成SwiftUI:

  1. 在扩展目标中创建新SwiftUI视图文件CustomNotificationView.swift:
import SwiftUI

struct CustomNotificationView: View {
    let title: String
    let subtitle: String
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(title)
                .font(.headline)
                .foregroundColor(.blue)
            Text(subtitle)
                .font(.subheadline)
                .foregroundColor(.gray)
            // 可添加自定义元素,比如图标、按钮等
            Image(systemName: "heart.fill")
                .foregroundColor(.red)
                .padding(.top, 8)
        }
        .padding()
    }
}
  1. 修改扩展的NotificationViewController.swift,将SwiftUI视图嵌入:
import UIKit
import UserNotifications
import UserNotificationsUI
import SwiftUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func didReceive(_ notification: UNNotification) {
        let content = notification.request.content
        // 将SwiftUI视图添加到当前控制器
        let hostingController = UIHostingController(rootView: CustomNotificationView(
            title: content.title,
            subtitle: content.subtitle
        ))
        addChild(hostingController)
        hostingController.view.frame = view.bounds
        view.addSubview(hostingController.view)
        hostingController.didMove(toParent: self)
    }
}

5. 测试自定义通知

  • 先添加通知权限请求:在AppDelegate的didFinishLaunchingWithOptions中加入:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    if granted {
        DispatchQueue.main.async {
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}
  • 运行主应用,调用testNotification()后将应用退到后台或锁屏,等待10秒即可看到自定义样式通知。
  • 调试扩展:在Xcode运行目标中选择你的Notification Extension,运行后触发通知即可断点调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:24