在Xamarin表单中推送通知

时间:2015-07-05 10:14:58

标签: ios xamarin push-notification xamarin.ios xamarin.forms

我试图在Xamarin表单IOS中的PCL应用程序中实现推送通知。我有一个合适的配置文件和p12文件,我用来向本机应用程序发送通知,我在我的Xamarin表单上使用它,除了这些更改,我还需要做更多的事情吗?我在IOS项目中更改了AppDelegate,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace Punteam.iOS
{
 [Register ("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {

        String model = UIDevice.CurrentDevice.Model;
        String sysName = UIDevice.CurrentDevice.SystemName;
        String sysVer = UIDevice.CurrentDevice.SystemVersion;
        NSUserDefaults.StandardUserDefaults.SetString (model, "Model");
        NSUserDefaults.StandardUserDefaults.SetString (sysName, "sysName");
        NSUserDefaults.StandardUserDefaults.SetString (sysName, "sysVer");

        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);
        }

        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App());

        return base.FinishedLaunching(app, options);
    }
    //***********************************************************************************************
    //** RegisteredForRemoteNotifications                                                           *
    //***********************************************************************************************

    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!
        }

        // Save new device token 
        NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
    }
    //***********************************************************************************************
    //** ReceivedRemoteNotification                                                                 *
    //***********************************************************************************************

    public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
    {
        ProcessNotification(userInfo, false);
    }
    //***********************************************************************************************
    //** ProcessNotification                                                                        *
    //***********************************************************************************************

    void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
    {
        // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
        if (null != options && options.ContainsKey(new NSString("aps")))
        {
            //Get the aps dictionary
            NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

            string alertString = string.Empty;
            string paramString = string.Empty;

            if (aps.ContainsKey(new NSString("alert")))
                alertString = (aps[new NSString("alert")] as NSString).ToString();

            if (aps.ContainsKey(new NSString("param")))
                paramString = (aps[new NSString("param")] as NSString).ToString();

            if (!fromFinishedLaunching)
            {
                //Manually show an alert
                if (!string.IsNullOrEmpty(alertString))
                {
                    UIAlertView avAlert = new UIAlertView("Awesome Notification", alertString , null, 
                        NSBundle.MainBundle.LocalizedString("Cancel", "Cancel"),
                        NSBundle.MainBundle.LocalizedString("OK", "OK"));

                    avAlert.Clicked += (sender, buttonArgs) =>
                    {
                        if (buttonArgs.ButtonIndex != avAlert.CancelButtonIndex)
                        {
                            if (!string.IsNullOrEmpty(paramString))
                            {
//                              App.Current.MainPage = new NavigationPage(new PushNotifMessageDisplay(paramString));
                            }
                        }
                    };

                    avAlert.Show();
                }
            }
        }
    }
    //***********************************************************************************************
    //** FailedToRegisterForRemoteNotifications                                                     *
    //***********************************************************************************************

    public override void FailedToRegisterForRemoteNotifications (UIApplication application , NSError error)
    {
        new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
    }
 }
}

1 个答案:

答案 0 :(得分:1)

您可以查看推送通知here

的完整示例

关于iOS部分,这是发送到 AppDelegate 的相关代码:

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    var deviceTokenString = deviceToken.ToString().Replace("<","").Replace(">", "").Replace(" ", "");
    var notificationService = Resolver.Resolve<IPushNotificationService>();
    var pushNotificationRegister = Resolver.Resolve<IPushNotificationRegister>();

    if (pushNotificationRegister.ShouldSendToken(deviceTokenString))
    {
        var uid = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
        notificationService.AddPushToken(deviceTokenString, DeviceUtils.GetDeviceType(), uid);
    }
}

* IPushNotificationRegister - 检查令牌是否已发送到服务器(这样做是为了避免不必要的服务器请求)。

* IPushNotificationService - 将令牌发送到服务器的服务。

相关问题