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

Xamarin.iOS中如何在AppDelegate里判断当前激活页是否为NFC.xaml

Xamarin.iOS 仅在指定ContentPage激活时启动NFC会话的实现方案

你不需要在FinishedLaunching方法中判断页面状态,该方法是应用启动阶段的回调,此时应用页面还未完成渲染,无法正确判断当前激活的页面,也不适合在这个阶段做和页面绑定的功能初始化。

推荐直接通过ContentPage的生命周期事件配合消息通知实现,完全符合你只在NFC.xaml页面激活时启用NFC的需求,实现步骤如下:


步骤1:在NFC页面的生命周期中发送状态通知

修改NFC.xaml.cs,重写页面显示和消失的生命周期方法,发送对应消息通知原生层执行NFC会话的启停:

public partial class NFC : ContentPage
{
    public NFC()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        // 发送启动NFC会话的消息
        MessagingCenter.Send(this, "StartNFCSession");
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        // 发送停止NFC会话的消息
        MessagingCenter.Send(this, "StopNFCSession");
    }
}

步骤2:在AppDelegate中订阅消息处理NFC会话

修改AppDelegate.cs,移除FinishedLaunching中原有的NFC初始化逻辑,改为订阅对应消息执行启停操作:

public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    private NFCNdefReaderSession Session;
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());
        
        // 订阅启动NFC会话消息
        MessagingCenter.Subscribe<NFC>(this, "StartNFCSession", sender =>
        {
            // 避免重复创建会话
            if (Session == null)
            {
                Session = new NFCNdefReaderSession(this, null, true);
            }
            Session?.BeginSession();
        });

        // 订阅停止NFC会话消息
        MessagingCenter.Subscribe<NFC>(this, "StopNFCSession", sender =>
        {
            Session?.InvalidateSession();
            Session = null;
        });

        return base.FinishedLaunching(app, options);
    }
}

补充说明

如果你确实有需要在任意位置判断当前激活页面是否为NFC页面,可以使用以下工具方法:

private bool IsNFCPageActivated()
{
    var mainPage = App.Current.MainPage;
    // 适配导航页结构
    if (mainPage is NavigationPage navPage)
    {
        return navPage.CurrentPage is NFC;
    }
    // 适配Shell结构
    if (mainPage is Shell shell)
    {
        return shell.CurrentPage is NFC;
    }
    // 单页面结构直接判断
    return mainPage is NFC;
}

注意该方法不能在FinishedLaunching中调用,此时页面还未加载完成,返回值永远为false。
另外使用MessagingCenter时可以在应用退出时调用MessagingCenter.Unsubscribe取消订阅,避免潜在的内存泄漏问题,同时提前确认Info.plist中已经配置了NFC相关权限,否则会话会启动失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:39:03