使用 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 中啟動時,可以直接執行此程式碼。或者,只要使用者決定要啟用推送通知,你就可以執行此操作。

執行此程式碼將觸發警報,提示使用者是否接受應用程式可以向其傳送通知。所以還要實現一個使用者否認的場景!

StackOverflow 文件

這些是需要實現在 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();
}

收到通知後,這就是它的樣子。

StackOverflow 文件