Сейчас я разрабатываю приложение MAUI для iOS, поэтому включил iOS в качестве целевой платформы. Целевая среда выполнения .Net — .Net 9, а минимальная целевая платформа iOS — 16.0.

Я реализовал функцию push-уведомлений, добавив проект расширения службы уведомлений (NSE) в Visual Studio Windows.
Для основного приложения и NSE я создал Идентификатор приложения. Для основного приложения, идентификатора приложения я включил возможности push-уведомлений и групп приложений, а для проекта NSE я включил возможность группы приложений на портале разработчиков Apple. Я создал группу приложений (group.com.company.id.name) и настроил идентификатор приложения как для основного приложения, так и для проекта NSE.
В файле App.xaml.cs я инициализировал OneSignal, как показано ниже:
Код: Выделить всё
OneSignal.Initialize("OneSignal_App_Id");
OneSignal.Notifications.RequestPermissionAsync(true);
Info.plist главного приложения
Код: Выделить всё
LSRequiresIPhoneOS
UIDeviceFamily
1
UIRequiredDeviceCapabilities
arm64
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UISupportedInterfaceOrientations~ipad
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
XSAppIconAssets
Assets.xcassets/appicon.appiconset
CFBundleShortVersionString
0.1
CFBundleVersion
1.0.0
CFBundleIdentifier
com.company.id.name
CFBundleDisplayName
Mobile app
CFBundleName
Mobile app
MinimumOSVersion
16.0
NSCameraUsageDescription
We need camera access to capture images.
CFBundleURLTypes
CFBundleURLSchemes
com.googleusercontent.apps.reverseClientId
UIBackgroundModes
fetch
remote-notification
OneSignal_app_groups_key
group.com.company.id.name.onesignal
Код: Выделить всё
aps-environment
development
com.apple.security.application-groups
group.com.company.id.name.onesignal
Код: Выделить всё
net9.0-android35.0;net9.0-ios18.0
Exe
true
true
enable
16.0
true
false
None
Platforms\iOS\Entitlements.plist
true
Код: Выделить всё
CFBundleDisplayName
OneSignalNotificationServiceExtension
CFBundleName
OneSignalNotificationServiceExtension
CFBundleIdentifier
com.company.id.name.OneSignalNotificationServiceExtension
CFBundlePackageType
XPC!
CFBundleShortVersionString
0.1
CFBundleVersion
1.0.0
NSExtension
NSExtensionPointIdentifier
com.apple.usernotifications.service
NSExtensionPrincipalClass
NotificationService
UIBackgroundModes
remote-notification
MinimumOSVersion
16.0
OneSignal_app_groups_key
group.com.company.id.name.onesignal
Код: Выделить всё
com.apple.security.application-groups
group.com.company.id.name.onesignal
Код: Выделить всё
net9.0-ios18.0
Library
enable
true
16.0
True
ios-arm64
com.company.id.name.OneSignalNotificationServiceExtension
Entitlements.plist
Entitlements.plist
Код: Выделить всё
using System;
using Foundation;
using OneSignalSDK.DotNet;
using OneSignalSDK.DotNet.iOS;
using UIKit;
using UserNotifications;
namespace OneSignalNotificationServiceExtension
{
[Register("NotificationService")]
public class NotificationService : UNNotificationServiceExtension
{
Action ContentHandler { get; set; }
UNMutableNotificationContent BestAttemptContent { get; set; }
UNNotificationRequest ReceivedRequest { get; set; }
protected NotificationService(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic,
// it only exists so that the OS can instantiate an instance of this class.
}
public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action contentHandler)
{
Console.WriteLine("DidReceive**********************");
ReceivedRequest = request;
ContentHandler = contentHandler;
BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
NotificationServiceExtension.DidReceiveNotificationExtensionRequest(request, BestAttemptContent, contentHandler);
}
public override void TimeWillExpire()
{
NotificationServiceExtension.ServiceExtensionTimeWillExpireRequest(ReceivedRequest, BestAttemptContent);
ContentHandler(BestAttemptContent);
}
}
}
Код: Выделить всё
var notification = new Notification(appId: _AppId)
{
Contents = new StringMap(en: message),
IncludeExternalUserIds = externalUserId,
IosBadgeType = "Increase",
IosBadgeCount = 1,
MutableContent = true
};
Я соединил Visual Studio Windows с Mac. Я получаю Push-уведомления в своем приложении. В Центре уведомлений отображается правильное количество, но проблема в том, что количество значков значков приложений не увеличивается, оно застряло только на 1.
Я думаю, что NSE не работает, потому что если я добавляю какой-либо префикс в тело метода DidReceiveNotification, он не отображается.
Я получаю ошибку ниже:
Код: Выделить всё
INFO: An error occurred while forwarding HotReload local tunnel: System.IO.IOException: USB connect timeout (ENODATA), likely because the app failed to launch. Please review device logs and/or crash reports for more information.
at Xamarin.MacDev.AggregateAsyncResult.CheckError(Boolean cancelled)
at Xamarin.MacDev.IPhoneDevice.EndConnectStream(IAsyncResult result)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location ---
at Xamarin.Messaging.IDB.IPhoneUsbLocalTunnelConnection.StartLocalTunnelAsync()
at Xamarin.Messaging.IDB.LaunchAppMessageHandler.ForwardLocalTunnelsAsync(LaunchAppMessage, IPhoneDevice)
ERROR: [iOS HotReload] Failed to connect to "iPhone" over USB on port 11000.
Есть ли что-то, что мне не хватает, из-за чего количество значков не увеличивается? Если между основным приложением и NSE нет связи, что нужно сделать?
Подробнее здесь: https://stackoverflow.com/questions/798 ... n-ios-maui
Мобильная версия