app delegate:
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("token");
// 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, "token");
IOSUserPreferences userPreference = new IOSUserPreferences();
userPreference.SetString("token", DeviceToken);
}
我的PCL界面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace neoFly_Montana
{
public interface IUserPreferences
{
void SetString(string key, string value);
string GetString(string key);
}
}
当我在pcl中调用接口时:
string token = App.UserPreferences.GetString("token");
App.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace neoFly_Montana
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new Views.Splash2()) { BarTextColor = Color.FromHex("#f98e1e") };
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
public static IUserPreferences UserPreferences { get; private set; }
public static void Init(IUserPreferences userPreferencesImpl)
{
App.UserPreferences = userPreferencesImpl;
}
}
}
关于iphone项目:
using Foundation;
using System;
using System.Collections.Generic;
using System.Text;
namespace neoFly_Montana.iOS
{
class IOSUserPreferences : IUserPreferences
{
public void SetString(string key, string value)
{
NSUserDefaults.StandardUserDefaults.SetString(value, key);
}
public string GetString(string key)
{
return NSUserDefaults.StandardUserDefaults.StringForKey(key);
}
}
}
在Android上它运行正常,保存并获取数据......
作为测试,我试图保存数据并将其放在app delegate上并且工作正常,我可以看到它访问IOSUserPreferences脚本,当我尝试在pcl上获取它时会出现问题
当我尝试获取保存的数据时,仅在ios中,它为null并且应用程序崩溃...我注意到它没有访问iphone项目上的获取字符串方法。 。 有人知道发生了什么吗?