我试图找到一种方法让用户可以找到他们的设备令牌(出于调试原因)。
...
@interface MyAppDelegate : UIResponder <UIApplicationDelegate> {
NSString *token;
}
@property (nonatomic, retain) NSString *token;
...
...
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
_token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
_token = [_token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSUInteger lenthtotes = [_token length];
NSUInteger req = 64;
if (lenthtotes == req){
NSLog(@"uploaded token: %@", _token);
upload_token = _token;
} else {
_token = @"";
}
...
NSString *token;
- (void)viewDidLoad
{
[super viewDidLoad];
MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
token = appDelegate.token;
NSLog(token);
...
AppDelegate
中的日志正常工作并返回设备令牌。
但是ViewController
里面的日志什么都没有回来?
答案 0 :(得分:2)
您无法以这种方式检索令牌是正常的,因为在您的视图控制器的viewDidLoad
方法中,您还没有获得令牌。
您应该推送,而不是从AppDelegate
检索。我会使用一个通知:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [_token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSUInteger lenthtotes = [_token length];
NSUInteger req = 64;
if (lenthtotes == req) {
NSLog(@"uploaded token: %@", token);
NSNotification *notif = [NSNotification notificationWithName:@"NEW_TOKEN_AVAILABLE" object:token];
[[NSNotificationCenter defaultCenter] postNotification:notif];
}
...
}
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tokenAvailableNotification:)
name:@"NEW_TOKEN_AVAILABLE"
object:nil];
}
- (void)tokenAvailableNotification:(NSNotification *)notification {
NSString *token = (NSString *)notification.object;
NSLog(@"new token available : %@", token);
}
- (void)dealloc {
[NSNotificationCenter defaultCenter] removeObserver:self];
}
答案 1 :(得分:0)
最简单的方法是从通知委托方法中获取它:
@interface MyAppDelegate : UIResponder <UIApplicationDelegate>
{
// No need to define backing variables
}
@property (nonatomic, retain) NSString *token;
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
self.token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
}
请注意,您必须使用与启用APNS的应用ID相关联的配置文件进行编译。如果未正确配置APNS,则可能无法收到令牌。
作为旁注,在使用属性时无需定义实例变量。编译器将处理设置后备变量,并管理所有这些变量;你只需定义@property并通过预定义的setter和getters(self.variableName)访问它。