azure - 设备未以 xamarin 形式在 azure 推送通知中心注册

标签 azure xamarin.ios xamarin.forms azure-notificationhub

我正在尝试在开发模式下在 azure 推送通知中心中使用标记注册设备 token ,但在 azure 门户中它显示已注册 0 个事件设备,当我检查通知中心时,它将显示发生了一个注册。

这是我的示例代码:

应用程序委托(delegate):

      var deviceTokenDes = deviceToken.Description;

        if (!string.IsNullOrWhiteSpace(deviceTokenDes))
        {
            deviceTokenDes = deviceTokenDes.Trim('<');
            deviceTokenDes = deviceTokenDes.Trim('>');
            deviceTokenDes = deviceTokenDes.Replace(" ", "");

            DeviceToken = deviceTokenDes.Trim('<');
            DeviceToken = deviceTokenDes.Trim('>');
            DeviceToken = deviceTokenDes.Replace(" ", "");
        }

        Hub = new SBNotificationHub(myapp.ListenConnectionString, myapp.NotificationHubName);

登录 View 模型:

   var tags = new List<string> { userId };

        AppDelegate.Hub?.UnregisterAllAsync(AppDelegate.DeviceToken, error =>
        {
            if (error != null)
            {
                Console.WriteLine("Error calling Unregister: {0}", error);
            }

            AppDelegate.Hub.RegisterNativeAsync(AppDelegate.DeviceToken, new NSSet(tags.ToArray()), errorCallback =>
            {
                if (errorCallback != null)
                {
                    Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
                }
            });

用户成功登录应用程序后,我已使用标签注册了设备 token 。你能建议一下吗? enter image description here

最佳答案

这就是我们在 AppDelegate 类中所做的全部事情。

public override async void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            bool ShouldComplete = true;

            // Validate if we have already got a registration
            try
            {
                string validation = NSUserDefaults.StandardUserDefaults.StringForKey("InitialTagRegistration");
                if (validation.Contains("Completed"))
                {
                    ShouldComplete = false;
                }
            }
            catch (Exception genEx)
            {
                ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx);
            }

            Hub = new SBNotificationHub(ConfigurableSettings.NotificationHubConnectionString, ConfigurableSettings.NotificationHubPathName);

            ApplicationState.SetValue("NotificationHub", Hub);

            // Get previous device token
            NSData oldDeviceToken = await ApplicationSettings.RetrieveDeviceToken();

            // If the token has changed unregister the old token and save the new token to UserDefaults.
            if (oldDeviceToken != null)
            {
                if (oldDeviceToken.ToString() != deviceToken.ToString())
                {
                    try
                    {
                        Hub.UnregisterAllAsync(oldDeviceToken, (error) =>
                        {
                            //check for errors in unregistration process.
                            if (error != null)
                            {
                                ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + error + " | Source: " + "Unregistering old device token against the notification hub.");
                                //exit out of the code here because we can't keep our hub clean without being able to remove the device from our registration list.
                                return;
                            }
                            else
                            {
                                ShouldComplete = true;
                            }
                        });
                    }
                    catch (Exception genEx)
                    {
                        ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx + Environment.NewLine + Environment.NewLine);
                    }
                }
            }
            else
            {
                // Store current device token 
                bool res = await ApplicationSettings.CacheDeviceToken(deviceToken);
            }

            // Check if we need to perform our initial registrations

            if (ShouldComplete)
            {
                NSSet RegisteredTags = await ApplicationSettings.RetrieveUserTags();

                if (RegisteredTags == null)
                {
                    RegisteredTags = new NSSet("AppleDevice");
                }

                //Register the device against the notification hub keeping the details accurate at all times.
                Hub.RegisterNativeAsync(deviceToken, RegisteredTags, (errorCallback) =>
                {
                    if (errorCallback != null)
                    {
                        ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + errorCallback + " | Source: " + "Registering device token against the notification hub.");
                    }
                    else
                    {
                        if (deviceToken != null)
                        {
                            NSUserDefaults.StandardUserDefaults.SetString("Completed", "InitialTagRegistration");
                            NSUserDefaults.StandardUserDefaults.Synchronize();
                        }
                    }
                });
            }
        }

总而言之,在将设备 token 传递到 azure 通知中心之前,您不需要对设备 token 执行任何操作。这就是为我们解决了问题的原因,我们的应用程序已经在事件应用程序中运行了几个月,没有任何问题。希望这会有所帮助。

编辑:为了在用户登录时更新标签,我们存储设备 token 以供稍后使用,并且当用户登录时,我们在单独的类中使用以下方法来方便更新标签:

    public static async Task<bool> UpdateTags(StaffProfile user)
    {
        //Get the instance of the Notification hub
        SBNotificationHub UpdateHub = new SBNotificationHub(ConfigurableSettings.NotificationHubConnectionString, ConfigurableSettings.NotificationHubPathName);
    //Grab the current device token that was stored during the start up process.
    NSData CurrentDeviceToken = await ApplicationSettings.RetrieveDeviceToken();

    //Get and create the tags we want to use.

    string EmailTag = string.Empty;
    string StoreTag = string.Empty;
    string OrganisationTag = "AppleDevice:OrgTag";
    string GenericTag = "AppleDevice:StaffTag";

    if (!string.IsNullOrWhiteSpace(user.Email))
    {
        EmailTag = user.Email;
        //Remove unwanted spaces and symbols.
        EmailTag = EmailTag.Replace(" ", "");
        EmailTag = string.Format("AppleDevice:{0}", EmailTag);
    }

    if (!string.IsNullOrWhiteSpace(user.Store?.Name))
    {
        StoreTag = user.Store.Name;
        //Remove unwanted space.
        StoreTag = StoreTag.Replace(" ", "");
        StoreTag = string.Format("AppleDevice:{0}", StoreTag);
    }

    //Create array of strings to the currently fixed size of 3 items.
    NSString[] TagArray = new NSString[4];

    //Only add in the tags that contain data.
    if (!string.IsNullOrEmpty(EmailTag)) { TagArray[0] = (NSString)EmailTag; }
    if (!string.IsNullOrEmpty(StoreTag)) { TagArray[1] = (NSString)StoreTag; }
    if (!string.IsNullOrEmpty(OrganisationTag)) { TagArray[2] = (NSString)OrganisationTag; }
    if (!string.IsNullOrEmpty(GenericTag)) { TagArray[3] = (NSString)GenericTag; }

    NSSet tags = new NSSet(TagArray);

    // Store our tags into settings
    ApplicationSettings.CacheUserTags(tags);

    try
    {
        if (CurrentDeviceToken == null)
        {
            ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: Device token is empty." + Environment.NewLine + Environment.NewLine);
        }
        else
        {
            UpdateHub.RegisterNativeAsync(CurrentDeviceToken, tags, (error) =>
            {
                //check for errors in unregistration process.
                if (error != null)
                {
                    ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + error + " | Source: " + "Registering against hub with new tags." + Environment.NewLine + Environment.NewLine);

                    // Lets do this so that we can force the initial registration to take place again.
                    NSUserDefaults.StandardUserDefaults.SetString("Failed", "InitialTagRegistration");
                    NSUserDefaults.StandardUserDefaults.Synchronize();
                }
                else
                {
                    ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[INFORMATION] - Message: Successful Registration - Source: Registering against hub with new tags." + Environment.NewLine + Environment.NewLine);
                }
            });
        }
    }
    catch (Exception genEx)
    {
        ApplicationLog.AppendFile(DateTime.Now.ToString() + "  :  " + "[PNS EXCEPTION] - Exception has been hit! - Message: " + genEx.Message + " | Source: " + genEx + Environment.NewLine + Environment.NewLine);
    }

    return await Task.FromResult(true);
}

关于azure - 设备未以 xamarin 形式在 azure 推送通知中心注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668244/

相关文章:

ios - Xamarin.iOS statusBar BackgroundColor不会更改

xamarin.ios - 单色触摸 : NameResolutionError when running on device

c# - 适用于 Windows Phone(8.1 和 10)平台的 Xamarin Forms 中的滑动手势识别器

android - Xamarin.Forms Visual Studio 2017 项目未部署

c# - 如何在 xamarin 跨平台中更改编辑器底部边框线颜色

azure - 不使用应用程序测试 Azure 通知中心

asp.net - "Mail sending denied"

azure - PowerShell Azure Blob 存储排除特定内容类型

azure - 最佳实践 : Calling separate Web-API Service from Single Page Application (SPA)

.net - 如何在 MonoTouch 中使用 System.IO.Packaging