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

Content Extension自定义UI按钮:关闭通知/打开APP实现方法咨询

嘿,我之前做通知内容扩展的时候也碰到过这个问题,给你两个靠谱的解决办法:

解决通知内容扩展中关闭通知或打开APP的问题

1. 直接关闭通知扩展视图(收起通知)

在你的按钮点击方法里,调用extensionContext的dismissNotificationContentExtension方法就能直接关闭扩展视图,同时通知会被正常收起:

- (IBAction)testCustomDismissDidTouch:(id)sender {
    // 关闭通知扩展并收起通知
    [self.extensionContext dismissNotificationContentExtension];
}

这个是UNNotificationContentExtension协议提供的标准方法,专门适配你开启了UNNotificationExtensionUserInteractionEnabled的场景,完美解决通知一直保持打开的问题。

2. 打开主APP(同时自动关闭通知)

如果想点击按钮直接跳转到主APP,得先给主APP配置自定义URL Scheme,然后在扩展里调用extensionContext的openURL:completionHandler:方法:

第一步:给主APP配置URL Scheme

打开主APP的Info.plist,添加CFBundleURLTypes数组,示例配置如下(把mycustomapp换成你自己的Scheme名称):

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>mycustomapp</string>
        </array>
    </dict>
</array>

第二步:在扩展里写跳转代码

- (IBAction)testCustomDismissDidTouch:(id)sender {
    // 替换成你刚才配置的URL Scheme
    NSURL *appURL = [NSURL URLWithString:@"mycustomapp://"];
    
    [self.extensionContext openURL:appURL completionHandler:^(BOOL success) {
        if (success) {
            NSLog(@"成功跳转到主APP啦");
        } else {
            NSLog(@"跳转失败,检查下URL Scheme是不是配错了");
        }
    }];
}

调用openURL之后,通知扩展会自动关闭,不用额外调用dismiss方法。要是跳转失败,90%是URL Scheme配置的问题,回去检查下主APP的Info.plist就行。

额外小技巧:标记通知为已读(可选)

如果想在关闭通知的同时把它标记为已读(从通知中心移除),可以结合UNUserNotificationCenter的API:

- (IBAction)testCustomDismissDidTouch:(id)sender {
    // 获取当前通知的唯一标识
    NSString *notificationID = self.notification.request.identifier;
    
    // 从通知中心移除这条通知
    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notificationID]];
    
    // 关闭扩展视图
    [self.extensionContext dismissNotificationContentExtension];
}

这样操作后,用户再看通知中心就看不到这条通知了,相当于标记为已读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:31:36