我正在使用 MvvmCross 5.1.1 和 MvvmCross.Forms 5.1.1
开发应用程序我在我的PCL项目中有一个CoreApp,我开始提供服务:
public class CoreApp : MvvmCross.Core.ViewModels.MvxApplication
{
void prepareRestServices() {
var httpClient = new HttpClient(new HttpLoggingHandler())
{
BaseAddress = new Uri(SharedConfig.BASE_API_URL),
Timeout = TimeSpan.FromMinutes(SharedConfig.TIMEOUT_OPERATION_MINUTES)
};
// Register REST services
Mvx.RegisterSingleton<IAuthenticationRestService>(() => RestServiceFactory.getService<IAuthenticationRestService>(httpClient));
Mvx.RegisterSingleton<IParentsRestService>(() => RestServiceFactory.getService<IParentsRestService>(httpClient));
Mvx.RegisterSingleton<IChildrenRestService>(() => RestServiceFactory.getService<IChildrenRestService>(httpClient));
Mvx.RegisterSingleton<IDeviceGroupsRestService>(() => RestServiceFactory.getService<IDeviceGroupsRestService>(httpClient));
}
void prepareMappers() {
Mapper.Initialize(cfg => {
cfg.CreateMap<ParentDTO, ParentEntity>();
cfg.CreateMap<SonDTO, SonEntity>();
cfg.CreateMap<DeviceDTO, DeviceEntity>();
});
}
public override void Initialize()
{
prepareRestServices();
prepareMappers();
CreatableTypes()
.InNamespace("Bullytect.Core.Services")
.EndingWith("ServiceImpl")
.AsInterfaces()
.RegisterAsLazySingleton();
Mvx.RegisterType<IValidator, Validator>();
Mvx.RegisterSingleton<IUserDialogs>(() => UserDialogs.Instance);
RegisterAppStart(new CustomAppStart());
}
}
另一个继承自MvxFormsApplication的App类,用于配置I18N并通过应用程序事件和FCM通知进行注册。
public partial class App : MvxFormsApplication
{
private void ConfigLocale()
{
if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Android)
{
var ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
AppResources.Culture = ci; // set the RESX for resource localization
DependencyService.Get<ILocalize>().SetLocale(ci); // set the Thread for locale-aware methods
}
}
public App()
{
ConfigLocale();
InitializeComponent();
}
void OnAuthenticatedUserMessage(AuthenticatedUserMessage authenticatedUserMessage)
{
Debug.WriteLine("OnAuthenticatedUserMessage ...");
var deviceGroupsService = Mvx.Resolve<IDeviceGroupsService>();
// save token
deviceGroupsService.saveDevice(CrossDeviceInfo.Current.Id, Settings.FcmToken).Subscribe(device => {
Debug.WriteLine(String.Format("Device Saved: {0}", device.ToString()));
});
}
void OnExceptionOcurredMessage(ExceptionOcurredMessage exceptionOcurredMessage)
{
Debug.WriteLine("OnExceptionOcurredMessage ...");
var userDialogs = Mvx.Resolve<IUserDialogs>();
userDialogs.ShowError(AppResources.Global_ErrorOcurred);
if (exceptionOcurredMessage.Ex != null)
exceptionOcurredMessage.Ex.Track();
}
protected override void OnStart()
{
Debug.WriteLine("Forms App OnStart ...");
var messenger = Mvx.Resolve<IMvxMessenger>();
// subscribe to Authenticated User Message
messenger.Subscribe<AuthenticatedUserMessage>(OnAuthenticatedUserMessage);
// subscribe to Exception Ocurred Message
messenger.Subscribe<ExceptionOcurredMessage>(OnExceptionOcurredMessage);
//Handling FCM Token
CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
{
Debug.WriteLine($"TOKEN REC: {p.Token}");
Settings.FcmToken = p.Token;
};
Debug.WriteLine($"TOKEN: {CrossFirebasePushNotification.Current.Token}");
Settings.FcmToken = CrossFirebasePushNotification.Current.Token;
}
}
问题是 onStart方法永远不会被调用,我没有其他地方可以初始化这些组件。
然后我还将 MvxFormsApplicationDelegate 和 MvxFormsIosSetup 的代码放在一起。
[Register("AppDelegate")]
public partial class AppDelegate : MvxFormsApplicationDelegate
{
public override UIWindow Window { get; set; }
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Window = new UIWindow(UIScreen.MainScreen.Bounds);
global::Xamarin.Forms.Forms.Init();
var setup = new Setup(this, Window);
setup.Initialize();
var startup = Mvx.Resolve<IMvxAppStart>();
startup.Start();
XFGloss.iOS.Library.Init();
LoadApplication(setup.FormsApplication);
Window.MakeKeyAndVisible();
FirebasePushNotificationManager.Initialize(options, true);
return true;
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
#if DEBUG
FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken, FirebaseTokenType.Sandbox);
#endif
#if RELEASE
FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken,FirebaseTokenType.Production);
#endif
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);
}
// To receive notifications in foregroung on iOS 9 and below.
// To receive notifications in background in any iOS version
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired 'till the user taps on the notification launching the application.
// If you disable method swizzling, you'll need to call this method.
// This lets FCM track message delivery and analytics, which is performed
// automatically with method swizzling enabled.
FirebasePushNotificationManager.DidReceiveMessage(userInfo);
// Do your magic to handle the notification data
System.Console.WriteLine(userInfo);
}
public override void OnActivated(UIApplication uiApplication)
{
FirebasePushNotificationManager.Connect();
base.OnActivated(uiApplication);
}
public override void DidEnterBackground(UIApplication application)
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
FirebasePushNotificationManager.Disconnect();
}
}
MvvmFormsIOSSetup
public class Setup : MvxFormsIosSetup
{
public Setup(IMvxApplicationDelegate applicationDelegate, UIWindow window)
: base(applicationDelegate, window)
{
}
protected override IMvxApplication CreateApp()
{
return new CoreApp();
}
protected override MvvmCross.Forms.Core.MvxFormsApplication CreateFormsApplication()
{
return new App();
}
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
protected override IMvxIosViewPresenter CreatePresenter()
{
return new CustomPresenter(Window, FormsApplication);
}
}
有谁知道为什么不调用这个方法?我的配置有问题吗?
非常感谢你。