我正在处理推送通知。我编写了以下用于获取设备令牌的代码。
- (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);
}
我能够在设备上成功运行应用程序但无法在控制台上获取设备ID。
我对认证和配置文件没有任何问题。
答案 0 :(得分:127)
您必须使用以下代码来获取设备令牌: -
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"content---%@", token);
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
// kDeviceToken=tokenString
print("deviceToken: \(tokenString)")
}
答案 1 :(得分:14)
要获取令牌设备,您可以执行一些步骤:
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);
}
答案 2 :(得分:8)
以下代码用于检索设备令牌。
// 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);
答案 3 :(得分:6)
Wasif的答案的Swift版本:
Swift 2.x
var token = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
print("Token is \(token)")
Swift 3的更新
let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
答案 4 :(得分:4)
如果您仍未获得设备令牌,请尝试输入以下代码,以便注册您的设备以进行推送通知。
它也适用于ios8或更高版本。
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
答案 5 :(得分:4)
使用description
就是许多答案,wrong approach是consumer property-即使您可以使用它,它也会在iOS 13以上的版本中失效。
相反,您应确保使用实际的二进制数据,而不仅仅是对其的描述。 Andrey Gagan很好地解决了Objective C解决方案,但是幸运的是,它变得更加简单:
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()
答案 6 :(得分:3)
在您的Appdelegate中,使用didRegisterForRemoteNotificationsWithDeviceToken
方法:
NSString *deviceTokenString = deviceToken.description;
deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@"[< >]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, deviceTokenString.length)];
NSLog(deviceTokenString.description);
答案 7 :(得分:2)
从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];
}
它适用于iOS13及更低版本。
答案 8 :(得分:2)
iOS 13以上版本的目标C ,由Wasif Saood的答案提供
将以下代码复制并粘贴到AppDelegate.m中以打印设备APN令牌。
set-current-plot "Distribution"
plot [P_distribution] of turtles
set-plot-x-range 0 (max [b] of turtles)
答案 9 :(得分:1)
在构建设置中设置代码签名配置文件如果您有APN启用证书,那么您肯定会获得令牌ID。并删除
配置文件:自动
并设置为
配置文件:您的配置文件证书。
答案 10 :(得分:0)
在Swift 3中获取设备令牌
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device token: \(deviceTokenString)")
}
答案 11 :(得分:0)
在swift 3中获取设备令牌
[exec]
-Dorg.eclipse.jetty.util.log.class?=org.eclipse.jetty.util.log.Slf4jLog
答案 12 :(得分:0)
为了让设备令牌使用以下代码,您只能使用物理设备获取设备令牌。如果您必须在使用模拟器时发送设备令牌,则可以使用以下条件。
if(!(TARGET_IPHONE_SIMULATOR))
{
[infoDict setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"DeviceToken"] forKey:@"device_id"];
}
else
{
[infoDict setValue:@"e79c2b66222a956ce04625b22e3cad3a63e91f34b1a21213a458fadb2b459385" forKey:@"device_id"];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"My token is: %@", deviceToken);
NSString * deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"the generated device token string is : %@",deviceTokenString);
[[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:@"DeviceToken"];
}
答案 13 :(得分:0)
快捷键4 这对我有用:
第1步进入目标,点击添加功能,然后选择推送通知
在AppDelegate.swift中的步骤2 中添加以下代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (didAllow, error) in
}
UIApplication.shared.registerForRemoteNotifications()
return true
}
//Get device token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("The token: \(tokenString)")
}
答案 14 :(得分:0)
对于 Objective-C
iOS 13 推送令牌有一些变化
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = @"";
if (@available(iOS 13, *)) {
NSUInteger length = deviceToken.length;
if (length == 0) {
token = @"";
}
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *actualToken = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[actualToken appendFormat:@"%02x", buffer[i]];
}
token = [actualToken copy];
} else {
token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
}
NSLog(@"My token is: %@", token);
}
答案 15 :(得分:-1)
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Token\(token)")
}