我想在另一个类(例如Game1.cs)中使用deviceToken.Description的值。我需要以某种方式将deviceToken.Description保存在Program.cs中,但我不知道如何。我创建了变量MyToken来保存字符串,但是我不知道如何从另一个类访问MyToken。
如何保存deviceToken.Description的值,以便可以在另一个类中使用它?
namespace Pushtest.iOS
{
[Register("AppDelegate")]
class Program : UIApplicationDelegate
{
private static Game1 game;
private static string MyToken = "";
internal static void RunGame()
{
game = new Game1();
game.Run();
}
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
public override void FinishedLaunching(UIApplication app)
{
global::Xamarin.Forms.Forms.Init();
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
RunGame();
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
// Get current device token
var DeviceToken = deviceToken.Description;
if (!string.IsNullOrWhiteSpace(DeviceToken))
{
DeviceToken = DeviceToken.Trim('<').Trim('>');
}
// 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!
}
MyToken = DeviceToken;
// Save new device token
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
}
}
}
答案 0 :(得分:0)
如果您不想存储大量数据,可以将其存储在属性中,例如:
Application.Current.Properties["MyToken"] = $"{DeviceToken}";
在另一情况下,请通过以下方式使用它:
var token= Application.Current.Properties["MyToken"].ToString();
答案 1 :(得分:0)
由于您将DeviceToken
的值保存在Program类中:
NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
您可以通过以下方法获取其他类中的值:
string deviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");