我已经完成了以下操作:
- 在FCM控制台中创建了一个项目,并将iOS项目添加到其中。
- 下载了
GoogleService-Info.plist
并将其添加到Xamarin Forms IOS Project目录,并将构建操作设置为Bundlesource
。 - 在info.plist启用远程通知背景模式。
- 在应用程序的info.plist文件中添加了firbaseappdelegateproxyenabled,并将其设置为no。
- 创建了一个配置配置文件和分发证书,并将其安装到钥匙扣访问中。另外,在项目选项中映射这些证书。
- 上传的.p12证书在FCM控制台中。
- 添加了用于处理
AppDelegate.cs
中推送通知的代码。
我的代码:
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App("",""));
RequestPushPermissionsAsync();
_launchoptions = options;
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
Console.WriteLine(granted);
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
//Messaging.SharedInstance.RemoteMessageDelegate = this;
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
return base.FinishedLaunching(app, options);
}
NSDictionary _launchoptions;
public override void OnActivated(UIApplication uiApplication)
{
base.OnActivated(uiApplication);
if (_launchoptions != null && _launchoptions.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
{
var notfication = _launchoptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
PresentNotification(notfication);
}
_launchoptions = null;
}
async Task RequestPushPermissionsAsync()
{
var requestResult = await UNUserNotificationCenter.Current.RequestAuthorizationAsync(
UNAuthorizationOptions.Alert
| UNAuthorizationOptions.Badge
| UNAuthorizationOptions.Sound);
bool approved = requestResult.Item1;
NSError error = requestResult.Item2;
if (error == null)
{
if (!approved)
{
Console.Write("Permission to receive notification was not granted");
return;
}
var currentSettings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();
if (currentSettings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
{
Console.WriteLine("Permissions were requested in the past but have been revoked (-Settings app)");
return;
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
Console.Write($"Error requesting permissions: {error}.");
}
}
public async override void RegisteredForRemoteNotifications(
UIApplication application, NSData deviceToken)
{
//if (deviceToken == null)
//{
// // Can happen in rare conditions e.g. after restoring a device.
// return;
//}
//Console.WriteLine($"Token received: {deviceToken}");
// Get current device token
var DeviceToken = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(DeviceToken))
{
DeviceToken = DeviceToken.Trim('<').Trim('>');
}
Console.WriteLine($"deviceToken received: {deviceToken}");
Console.WriteLine($"DeviceToken received: {DeviceToken}");
// Get previous device token
var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
// Has the token changed?
if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
{
//TODO: Put your own logic here to notify your server that the device token has changed/been created!
}
// Save new device token
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
await SendRegistrationToServerAsync(DeviceToken);
}
async Task SendRegistrationTokenToMainPRoject(NSData deviceToken)
{
MessagingCenter.Send<object, string>(this, "fcmtoken", deviceToken.ToString());
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
Console.WriteLine($"Failed to register for remote notifications: {error.Description}");
}
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo,
Action<UIBackgroundFetchResult> completionHandler)
{
PresentNotification(userInfo);
completionHandler(UIBackgroundFetchResult.NoData);
try
{
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
var message = (aps[new NSString("webContentList")] as NSString).ToString();
LoadApplication(new App("", message));
}
catch (Exception ex)
{
//LogInfo.ReportErrorInfo(ex.Message, ex.StackTrace, "AppDelegate-DidReceiveRemoteNotification");
}
}
void PresentNotification(NSDictionary userInfo)
{
NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
var msg = string.Empty;
if (aps.ContainsKey(new NSString("alert")))
{
msg = (aps[new NSString("alert")] as NSString).ToString();
}
if (string.IsNullOrEmpty(msg))
{
msg = "(unable to parse)";
}
MessagingCenter.Send<object, string>(this, App.NotificationReceivedKey, msg);
}
}
我没有在iOS部分中使用任何Nuget软件包。将项目运行到设备中时,FCM令牌生成零件正在工作,我可以在VS控制台上看到FCM令牌。我试图将测试通知发送到邮递员的设备,但要获得InvalidRegistration
错误。
Postman响应
{
"multicast_id": 8754155136812875313,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Postman主体
{
"to" : "d20ad003 7473bfba 85dffc33 1534decf b4b886f1 c738878f fd7f2c60 d9dabc36",
"collapse_key" : "type_a",
"data" : {
"body" : "Body of Your Notification in Data",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
},
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification",
"sound": "default",
"content_available" : true
}
}
我已经完成了Android零件的实现,并在从邮递员开始时收到了通知。但是在iOS零件上获取InvalidRegistration
错误,并且在我的iOS设备上没有收到任何通知。
我遵循此YouTube视频以进行此实现,完整的源代码在此。
任何人建议解决这个问题。
预先感谢。
update
我创建了一个示例项目和一个邮递员,并将其添加到我的Google文件夹中。
Postman Collection包含2个REST API,一个用于Android设备,另一个用于iOS设备
如果您导入Postman Collection并运行Android REST API,我将收到通知,因为我在其中添加了设备FCM令牌。但是,在邮递员中运行iOS REST API时,将返回Postman中的InvalidRegistration
错误。
请浏览示例项目,请给我解决方案?
我已经审查了并可以解决此问题。
- 安装插件xamarin.firebase.ios.cloudmessaging iOS项目。
- AppDelegate类需要从Iunusernotificationcenterdelegate和Imessagingdelegate接口继承。
- 包括firebase.core.app.configure((;在注册远程通知之前完成刷新方法。
- 然后,您可以添加注册的远程通知代码(您可以从给定的链接中获取代码(。
- 您需要设置用户通知委托和消息传递共享Instant委托(unusernotificationcenter.current.delegate = this;//对于iOS 10显示通知(通过apns发送(和Messaging.sharedinstance.delegate.delegate = this;(。 li>包括具有相应属性的DidreceiveregistrationToken和Didreceivemessage方法
请参阅此AppDelegate类,以获取更多清晰度https://github.com/xamarin/googleapisforioscomponents/blob/master/master/firebase/firebase.cloudmessaging/samples/cloudmessagingsamplem-cloudmessagingsample/cloudmessampample/cloudmessampamplem
相关的Xamarin论坛线程https://forums.xamarin.com/discussion/159477/xamarin-forms-push-notification-is-not-receiving-to-ios-ios-ios-device#latest