我在Xamarin iOS应用中遇到Firebase FCM实施问题。
我的应用代表看起来像这样:
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public class AppDelegate : MvxApplicationDelegate, IUNUserNotificationCenterDelegate
{
// class-level declarations
public override bool WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
{
//base.WillFinishLaunching(application, launchOptions);
Window = new UIWindow(UIScreen.MainScreen.Bounds);
var launchScreen = (LaunchScreen)_launchStoryboard.InstantiateViewController("LaunchScreen");
Window.RootViewController = launchScreen;
this.SetWindow(Window);
Window.MakeKeyAndVisible();
return true;
}
public override UIWindow Window { get; set; }
//
// This method is invoked when the application is about to move from active to inactive state.
//
// OpenGL applications should use this method to pause.
//
public override void OnResignActivation(UIApplication application)
{
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public override void DidEnterBackground(UIApplication application)
{
var offline = Mvx.Resolve<IOfflineContent>();
offline.StopGpsWatcher();
Messaging.SharedInstance.Disconnect();
}
// This method is called as part of the transiton from background to active state.
public override void WillEnterForeground(UIApplication application)
{
var offline = Mvx.Resolve<IOfflineContent>();
offline.StartGpsWatcher();
}
// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate(UIApplication application)
{
}
private static UIStoryboard _launchStoryboard = UIStoryboard.FromName("Launch", null);
public override void FinishedLaunching(UIApplication application)
{
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler.CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += ExceptionHandler.TaskSchedulerOnUnobservedTaskException;
var presenter = new MvxTouchViewPresenter(this, Window);
var setup = new Setup(this, presenter);
setup.Initialize();
var startup = Mvx.Resolve<IMvxAppStart>();
startup.Start();
RegisterForNotificationFcm();
}
private void RegisterForNotificationFcm()
{
// get permission for notification
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10
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;
}
else
{
// iOS 9 <=
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
//ConnectFcm();
Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
{
var newToken = Firebase.InstanceID.InstanceId.SharedInstance.Token;
// if you want to send notification per user, use this token
System.Diagnostics.Debug.WriteLine(newToken);
ConnectFcm();
});
}
public override void OnActivated(UIApplication uiApplication)
{
base.OnActivated(uiApplication);
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
Messaging.SharedInstance.ApnsToken = deviceToken;
ConnectFcm();
}
// iOS 9 <=, fire when recieve notification foreground
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
Messaging.SharedInstance.AppDidReceiveMessage(userInfo);
// Generate custom event
NSString[] keys = { new NSString("Event_type") };
NSObject[] values = { new NSString("Recieve_Notification") };
var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);
// Send custom event
Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);
if (application.ApplicationState == UIApplicationState.Active)
{
System.Diagnostics.Debug.WriteLine(userInfo);
var aps_d = userInfo["aps"] as NSDictionary;
var alert_d = aps_d["alert"] as NSDictionary;
var body = alert_d["body"] as NSString;
var title = alert_d["title"] as NSString;
DebugAlert(title, body);
}
}
// iOS 10, fire when recieve notification foreground
[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
var title = notification.Request.Content.Title;
var body = notification.Request.Content.Body;
DebugAlert(title, body);
}
private void ConnectFcm()
{
try
{
Firebase.Core.App.Configure();
Messaging.SharedInstance.Connect((error) =>
{
if (error == null)
{
//Messaging.SharedInstance.Subscribe("/topics/all");
}
System.Diagnostics.Debug.WriteLine(error != null ? "error occured" : "connect success");
});
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
private void DebugAlert(string title, string message)
{
var alert = new UIAlertView(title ?? "Title", message ?? "Message", null, "Cancel", "OK");
alert.Show();
}
}
我在ConnectFCM方法中遇到错误“{操作无法完成。(com.google.fcm错误501。)}”
我在模拟器上测试它我认为在模拟器上它不起作用(我的意思是接收通知)但连接工作与否?我在真实设备上也尝试过,但同样的应用程序从开始崩溃....
答案 0 :(得分:0)
您应该在info.plist
。
<key>NSExceptionDomains</key>
<dict>
<key>firebaseio.com</key>
<dict>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>