English 中文(简体)
MAUI - 推动通知书支持
原标题:MAUI - push notifications support

我找不到任何文件,说明如何在马库里执行推动通知书。 也许有些人能够将Xamarin图书馆纳入Maui项目以完成吗?

问题回答

。 NET MAUI仍在审查之中,而“踢tir轮胎”正在发生许多事情,但任何人都不应在生产中使用。 部落以及文件和第三方图书馆仍在开发之中。

尽管如此,诸如推动通知等概念实际上赢得了很大变化。 平台特定层的缓冲通知仍然发生很多。 例如,如果你遵循,则请看看它指的是MainActative,尽管在另一个地方,但仍然有。 查阅<代码>AppDelegate。

你们必须把一些概念转化为。 NET MAUI, 但它过于复杂,无法加以说明。 但是,如果你能够开车,有时间,图书馆和文件会赶上更远的距离!

希望下面的理论将有助于您获得<>Firebase。 <MAUI Project on iOS.

Preparation

我认为,你已经恰当地确定了 Apple果供应情况。 这意味着你在 Apple果开发场设立了Certificate,IdentifierProfile(特别是Distribution - App Store)。 不要忘记在Identifier page上提供“普什通知”,供您使用,并使用Bundle ID。 http://www.kodeco.com/20201639-firebase-cloud-messaging-for-ios-push-notifications#toc-anchor-003“rel=” APN Key - 检查“Apple Push 通知服务”(APNs)——下载,并记住Key ID<>。 页: 1 消防局。

I also consider all preparation work on Firebase Console is done according to tutorial and you have the GoogleService-Info.plist file ready (but not added to your project). Do not forget to register APNs Authentication Key on page Project setting, tab "Cloud Messaging", part "Apple app configuration".

Project changes

所有这一切都使得可在Visualudio 2022上公开解决MAUI项目。 在我的案件版本17.3.6,NET SDK 6.0.402中,MAUI的工作量为6.0.541,建立了服务器MacOS Monterey 12.6 和Xcode 14.0.1。

项目特性中的“TargetOS”定在“net6.0-ios15.4”上,然后用传统方式添加“Xamarin.Firebase.iOS ±Messaging”版本8.10.0.2。

You can run into an issue with a long path. Package installation might fail with exception "System.IO.DirectoryNotFoundException: Could not find a part of the path C:Users....nugetpackagesxamarin.firebase.ios.installations...FirebaseInstallations-umbrella.h ." But you can solve it by adding Nuget.config file into solution folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <config>
    <clear />
    <add key="globalPackagesFolder" value="C:Nuget" />
  </config>
</configuration>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aps-environment</key>
    <string>development</string>
</dict>
</plist>

添加到Info.plist上。

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

您可以包括 谷歌-Info.plist。 在项目档案中增加这些线路:

<ItemGroup Condition=" $(TargetFramework) == net6.0-ios15.4 ">
    <BundleResource Include="PlatformsiOSGoogleService-Info.plist" />
</ItemGroup>

... and let the Firebase package to read settings from it but let s keep it simpler and do not add this file to project.

相反,如:

using Firebase.CloudMessaging;
using Foundation;
using UIKit;
using UserNotifications;

namespace ...

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        ...

        var result = base.FinishedLaunching(application, launchOptions);

        var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
        UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
        {
            this.Log($"RequestAuthorization: {granted}" + (error != null ? $" with error: {error.LocalizedDescription}" : string.Empty));

            if (granted && error == null)
            {
                this.InvokeOnMainThread(() =>
                {
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                    this.InitFirebase();
                });
            }
        });

        return result;
    }

    private void InitFirebase()
    {
        this.Log($"{nameof(this.InitFirebase)}");

        try
        {
            var options = new Firebase.Core.Options("[GOOGLE_APP_ID]", "[GCM_SENDER_ID]");
            options.ApiKey = "[API_KEY]";
            options.ProjectId = "[PROJECT_ID]";
            options.BundleId = "[BUNDLE_ID]";
            options.ClientId = "[CLIENT_ID]";

            Firebase.Core.App.Configure(options);
        }
        catch (Exception x)
        {
            this.Log("Firebase-configure Exception: " + x.Message);
        }

        UNUserNotificationCenter.Current.Delegate = this;

        if (Messaging.SharedInstance != null)
        {
            Messaging.SharedInstance.Delegate = this;
            this.Log("Messaging.SharedInstance SET");
        }
        else
        {
            this.Log("Messaging.SharedInstance IS NULL");
        }
    }

    // indicates that a call to RegisterForRemoteNotifications() failed
    // see developer.apple.com/documentation/uikit/uiapplicationdelegate/1622962-application
    [Export("application:didFailToRegisterForRemoteNotificationsWithError:")]
    public void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
    {
        this.Log($"{nameof(FailedToRegisterForRemoteNotifications)}: {error?.LocalizedDescription}");
    }

    // this callback is called at each app startup
    // it can be called two times:
    //   1. with old token
    //   2. with new token
    // this callback is called whenever a new token is generated during app run
    [Export("messaging:didReceiveRegistrationToken:")]
    public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
    {
        this.Log($"{nameof(DidReceiveRegistrationToken)} - Firebase token: {fcmToken}");

        //Utils.RefreshCloudMessagingToken(fcmToken);
    }

    // the message just arrived and will be presented to user
    [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
    public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        var userInfo = notification.Request.Content.UserInfo;

        this.Log($"{nameof(WillPresentNotification)}: " + userInfo);

        // tell the system to display the notification in a standard way
        // or use None to say app handled the notification locally
        completionHandler(UNNotificationPresentationOptions.Alert);
    }

    // user clicked at presented notification
    [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        this.Log($"{nameof(DidReceiveNotificationResponse)}: " + response.Notification.Request.Content.UserInfo);
        completionHandler();
    }

    void Log(string msg)
    {
        ...
    }
}

页: 1

Build and test

现在,你可以建设该项目!

Beware, Firebase iOS CloudMessaging works only in Release mode. In Debug mode Configure method fails with message "Could not create an native instance of the type Firebase.Core.Options : the native class hasn t been loaded", no matter you test on physical device with properly set manual Provisioning profile. So, we can test messaging using TestFlight or AdHoc distribution only.

发出测试通知信息最容易使用Firebase Console。 开放式 <<>><>> > <> >菜单和“回答你的第一个电文”栏。 在“认证案文”领域和“修正测试信息”栏目中,填充了实地的标语,“证明书登记号” (请从“你的”标识文档中查取)和“试验”纽吨。

Recommended links

此前的消防基地 使用了Id,但对此作了解释。 Soxamarin的包裹有工作。 你们可以使用消防站,但只能发送电文(fcm)。 此时不可能获得该装置。

这一非常简单的例子对我来说是完美的。 现在,我有消防基地的普什通知,在我的8网中工作。

https://github.com/coop-tim/maui-sample”rel=“nofollow noreferer”>https://github.com/coop-tim/maui-sample





相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...

热门标签