获取推送通知的设备令牌

jag*_*zzz 73 iphone push-notification apple-push-notifications ios appdelegate

我正在处理推送通知.我编写了以下代码来获取设备令牌.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    NSLog(@"Registering for push notifications...");    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
    NSLog(@"This is device token%@", deviceToken);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"Error %@",err);    
}
Run Code Online (Sandbox Code Playgroud)

我能够在设备上成功运行应用程序,但无法在控制台上获取设备ID.

我对认证和配置文件没有任何问题.

Was*_*ood 145

您必须使用以下代码来获取设备令牌: -

Objective-C的

+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
  NSUInteger dataLength = data.length;
  if (dataLength == 0) {
    return nil;
  }

  const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  return [hexString copy];
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
} 
Run Code Online (Sandbox Code Playgroud)

  • 然后,请检查您的配置文件,它应该是您为推送通知创建ssl证书的应用程序ID. (4认同)
  • 小心,不再使用“描述”属性:http://stackoverflow.com/questions/39495391/swift-3-device-tokens-are-now-being-parsed-as-32bytes (3认同)
  • 对于那些对Swift中的代码示例感兴趣的人:https://gist.github.com/sawapi/a7cee65e4ad95578​​044d (2认同)

Bki*_*est 13

要获得令牌设备,您可以通过以下步骤完成:

1)为开发人员认证和分发认证启用APNS(Apple推送通知服务),然后重新下载这两个文件.

2)重新下载Developer Provisioning和Distribute Provisioning文件.

3)在Xcode界面中:为具有两个文件配置的PROJECT和TARGETS设置配置已下载.

4)最后,您需要在AppDelegate文件中添加以下代码以获取令牌设备(注意:在真实设备中运行应用程序).

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     [self.window addSubview:viewController.view];
     [self.window makeKeyAndVisible];

     NSLog(@"Registering for push notifications...");    
     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
     return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
     NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
     NSLog(@"%@", str);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { 
     NSString *str = [NSString stringWithFormat: @"Error: %@", err];
     NSLog(@"%@",str);
}
Run Code Online (Sandbox Code Playgroud)


cds*_*per 12

使用description这些答案中的许多建议是错误的方法- 即使你让它工作,它也会在 iOS 13+ 中崩溃。

相反,您应该确保使用实际的二进制数据,而不仅仅是对它的描述。Andrey Gagan 很好地解决了 Objective C 解决方案,但幸运的是它在 swift 中要简单得多:

Swift 4.2适用于iOS 13+

// credit to NSHipster (see link above)
// format specifier produces a zero-padded, 2-digit hexadecimal representation
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
Run Code Online (Sandbox Code Playgroud)


Jak*_*nin 8

iOS 13+ 的 Objective C,由 Wasif Saood 的回答提供

将以下代码复制并粘贴到 AppDelegate.m 中以打印设备 APN 令牌。

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUInteger dataLength = deviceToken.length;
  if (dataLength == 0) {
    return;
  }
  const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  NSLog(@"APN token:%@", hexString);
}
Run Code Online (Sandbox Code Playgroud)


Nim*_*ekh 6

以下代码用于检索设备令牌.

    // Prepare the Device Token for Registration (remove spaces and < >)
    NSString *devToken = [[[[deviceToken description] 
                            stringByReplacingOccurrencesOfString:@"<"withString:@""] 
                           stringByReplacingOccurrencesOfString:@">" withString:@""] 
                          stringByReplacingOccurrencesOfString: @" " withString: @""];


    NSString *str = [NSString 
                     stringWithFormat:@"Device Token=%@",devToken];
    UIAlertView *alertCtr = [[[UIAlertView alloc] initWithTitle:@"Token is " message:devToken delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
    [alertCtr show];
    NSLog(@"device token - %@",str);
Run Code Online (Sandbox Code Playgroud)

  • 这从来不是正确的解决方案。切勿以`description`为基础。 (2认同)

Ant*_*ine 5

还有Swif版本的Wasif的答案:

Swift 2.x

var token = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
print("Token is \(token)")
Run Code Online (Sandbox Code Playgroud)

Swift 3的更新

let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
Run Code Online (Sandbox Code Playgroud)


And*_*gan 5

从 iOS 13 开始,Apple 更改了[deviceToken description]输出。现在它是这样的,这{length=32,bytes=0x0b8823aec3460e1724e795cba45d22e8...af8c09f971d0dabc}对于设备令牌是不正确的。

我建议使用此代码片段来解决问题:

+ (NSString *)stringFromDeviceToken:(NSData *)deviceToken {
    NSUInteger length = deviceToken.length;
    if (length == 0) {
        return nil;
    }
    const unsigned char *buffer = deviceToken.bytes;
    NSMutableString *hexString  = [NSMutableString stringWithCapacity:(length * 2)];
    for (int i = 0; i < length; ++i) {
        [hexString appendFormat:@"%02x", buffer[i]];
    }
    return [hexString copy];
}
Run Code Online (Sandbox Code Playgroud)

它适用于 iOS13 及更低版本。