【问题标题】:How to get the devicetoken in another class that is not the AppDelegate?如何在另一个不是 AppDelegate 的类中获取 devicetoken?
【发布时间】:2012-12-18 22:21:59
【问题描述】:

下午好。我是巴西人,如有任何英语错误,请见谅!

我正在向我自己的设备发送推送通知。我可以在我的AppDelegate.m 中获取我的 deviceToken:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {  
    NSLog(@"Device Token Global : %@", deviceToken);   
}

但是我有一个名为LoginViewController.m 的类,我在其中执行登录并将deviceToken 发布到网络服务(将其插入到mySQL 表中)。如何在我的 LoginViewController.m 类中将此 deviceToken 作为字符串获取?

【问题讨论】:

  • 在模型-视图-控制器方面,您目前对应用程序的模型组件有什么影响?

标签: ios xcode ios6 appdelegate devicetoken


【解决方案1】:

将令牌转换为字符串:

NSString *tokenString = [deviceToken description];
tokenString = [tokenString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; 
tokenString = [tokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

使用您选择的特定于应用程序的密钥将令牌存储到NSUserDefaults

[[NSUserDefaults standardUserDefaults] setObject:tokenString forKey:@"MyAppSpecificGloballyUniqueString"];

然后,在您应用的其他地方检索它:

NSString *tokenString = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppSpecificGloballyUniqueString"];

您没有使用NSUserDefaults。您可以使用任何类型的全局状态、单例对象、注册表或依赖注入来传递值。你如何做到这一点取决于你;这只是一个例子。

【讨论】:

  • 感谢以上代码。只有最后一行对我不起作用。我没有使用stringforKey,而是使用了objectforKey,然后它运行良好。 :)
  • 我试图解决这个问题几天,直到我找到你的版本,它工作得很好!谢谢!
【解决方案2】:

使用单例类并创建设备字符串(deviceString)。

singletonObject.deviceString = [deviceToken description];
singletonObject.deviceString = [tokenString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; 
singletonObject.deviceString = [tokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

现在您可以在任何其他类中使用 singletonObject.deviceString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多