首页 > 解决方案 > 我可以通过设备令牌获取注册吗?

问题描述

是否可以在不下载所有注册的情况下通过设备令牌找到设备?我应该将设备令牌添加为标签并根据它进行查找吗?

如果在同一设备上与新用户添加了新注册,我需要删除设备的先前注册。

标签: azureazure-notificationhub

解决方案


我将设备令牌添加为标签。Android 令牌需要两个标签,因为它们的长度超过了标签的最大长度。

public static string FormatDeviceTokenTag(int index, string token) => $"DEVICE_TOKEN{index}:{token}";    

public static IList<string> GetDeviceTokenTags(string token)
{
    const int MaxTagLength = 120;

    var tag0 = FormatDeviceTokenTag(0, token);

    var tag0Clipped = tag0.Substring(0, Math.Min(tag0.Length, MaxTagLength));

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

    if (tag0.Length > MaxTagLength)
    {
        var tag1 = FormatDeviceTokenTag(1, tag0.Substring(MaxTagLength));

        if (tag1.Length > MaxTagLength)
        {
           throw new ArgumentException("Token too long");
        }

        tags.Add(tag1);
    }

    return tags;
}

然后找到匹配的令牌...

async Task<IList<RegistrationDescription>> GetExistingRegistrations(string token, EnumMobileDeviceType deviceType)
{
    var tags = GetDeviceTokenTags(token);

    var registrations = await CreateClient().GetRegistrationsByTagAsync(tags.First(), 10000);

    var registrations2 = registrations.Where(r => tags.Count > 1 ?
        r.Tags.Contains(tags[1]) :
        !r.Tags.Any(t =>
            t.StartsWith(FormatDeviceTokenTag(1, string.Empty), StringComparison.Ordinal)));

    registrations2 = registrations2.Where(r =>
        (deviceType == EnumMobileDeviceType.Apple && r is AppleTemplateRegistrationDescription) ||
            (deviceType == EnumMobileDeviceType.Droid && r is GcmTemplateRegistrationDescription));

    return registrations2.ToList();
}

多么繁琐的工作啊。我错过了 API 中的某些内容吗?


推荐阅读