我有一个连接Azure后端服务的Xamarin.iOS应用程序,我希望我的服务向客户端应用程序发送通知。
Microsoft文档说明了如何为不同的方案设置通知中心。我想我已经掌握了大部分内容,但是我不确定我是否理解了very first part,它适用于来自Platform Notification Service的iOS应用程序Retrieve PNS Handle
,如下图所示:
看起来这是必须由客户端应用程序单独执行的一些任务,然后将其传递给后端服务以进行注册。
我有一种感觉,它发生在this section的第10步,当iOS调用应用程序回到RegisteredForRemoteNotifications
方法时。在该回调中,应用程序被赋予deviceToken
:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
Hub.UnregisterAllAsync (deviceToken, (error) => {
if (error != null)
{
System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
return;
}
NSSet tags = null; // create tags if you want
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
});
}
题
deviceToken
是我需要发送到后端服务以启动注册过程的PNS句柄吗?如果没有,我该如何联系PNS获取Handle?
RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
方法是告诉代理该应用程序已成功注册推送通知服务。
参数“deviceToken”是一个全局唯一令牌,用于将此设备标识为推送通知服务。
NSSet tags = null; // create tags if you want
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
{
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
由于您使用的是Azure,因此Hub已将令牌发送到上述方法中的生成远程通知。因此,如果您只想向所有用户推送一些内容,则无需执行其他操作。如果要推送给特定用户,可以注册一个标签并将其用作参数。
这些信息在documentation中,但对于C#开发人员来说并不是一个明显的形式。
在Objective-C中,deviceToken
是由iOS应用程序提供的,正如@LucasZ在PNS注册后所提到的那样。
但是我不能马上发送这个deviceToken
,因为它不会被我的服务中使用的AppleRegistrationDescription
类接受。
我花了一段时间才更熟悉Objective-C,以确定此令牌在发送到Azure之前实际已经转换:
NSSet* tagsSet = tags?tags:[[NSSet alloc] init];
NSString *deviceTokenString = [[token description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceTokenString = [[deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""] uppercaseString];
我在C#中实现了类似的东西:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
string pnsHandle = deviceToken.Description
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace(" ", string.Empty)
.ToUpper();
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
Hub.UnregisterAllAsync (pnsHandle, (error) =>
{
if (error != null)
{
System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
return;
}
// In my use case, the tags are assigned by the server based on privileges.
NSSet tags = null;
Hub.RegisterNativeAsync(pnsHandle, tags, (errorCallback) =>
{
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
});
}
要回答我的问题,是的,deviceToken
是PNS句柄,但必须格式化。