使用 Azure 推送 iOS 通知
要开始推送通知的注册,你需要执行以下代码。
// registers for push
var settings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert
| UIUserNotificationType.Badge
| UIUserNotificationType.Sound,
new NSSet());
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
当应用程序在 AppDelegate.cs
文件中的 FinishedLaunching
中启动时,可以直接运行此代码。或者,只要用户决定要启用推送通知,你就可以执行此操作。
运行此代码将触发警报,提示用户是否接受应用程序可以向其发送通知。所以还要实现一个用户否认的场景!
这些是需要实现在 iOS 上实现推送通知的事件。你可以在 AppDelegate.cs
文件中找到它们。
// We've successfully registered with the Apple notification service, or in our case Azure
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
// Modify device token for compatibility Azure
var token = deviceToken.Description;
token = token.Trim('<', '>').Replace(" ", "");
// You need the Settings plugin for this!
Settings.DeviceToken = token;
var hub = new SBNotificationHub("Endpoint=sb://xamarinnotifications-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=<your own key>", "xamarinnotifications");
NSSet tags = null; // create tags if you want, not covered for now
hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
{
if (errorCallback != null)
{
var alert = new UIAlertView("ERROR!", errorCallback.ToString(), null, "OK", null);
alert.Show();
}
});
}
// We've received a notification, yay!
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
NSObject inAppMessage;
var success = userInfo.TryGetValue(new NSString("inAppMessage"), out inAppMessage);
if (success)
{
var alert = new UIAlertView("Notification!", inAppMessage.ToString(), null, "OK", null);
alert.Show();
}
}
// Something went wrong while registering!
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
var alert = new UIAlertView("Computer says no", "Notification registration failed! Try again!", null, "OK", null);
alert.Show();
}
收到通知后,这就是它的样子。