我正在处理推送通知。我编写了以下代码来获取设备令牌。
- (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。
我对认证和配置文件没有任何问题。
注意:以下解决方案不再适用于iOS 13+设备- 它会返回垃圾数据。
请改用以下代码:
+ (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];
}
在iOS 13之前可以使用的解决方案:
- (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);
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}
然后,请检查您的配置文件,该文件应该是您创建用于推送通知的ssl证书的应用ID。
您需要将代码添加到AppDelegate文件@jagzzz
对于那些对用Swift编写的代码示例感兴趣的人:gist.github.com/sawapi/a7cee65e4ad95578044d
小心,不再使用“描述”属性:stackoverflow.com/questions/39495391/…
@codester我已经使用Xcode 10.3上传了我的构建,它是实时的。按照您的声明,Objective C方法将继续破坏XCode 11,但我在数据库中看到的是它显示的是数据长度,而不是正确的apns令牌字符串。所以我只想知道,这取决于Xcode版本还是iOS版本(即13. *)?