1

在我的应用程序中,在 appDelegate 文件中,我注册了毛皮推送通知,获取令牌并获取设备 UDID。我将这些变量保存为全局变量。

我要做的下一件事是在我的 viewController 中使用这两个变量连接到一个 URL。

但是,当我从我的 viewController 调用变量时,它们是(null)。

所以我想也许我对他们做错了什么。但即使我在 appdelegate() 和 viewcontroller() 上 nslog 某些内容,它也会首先从 viewcontroller nslogs ...

这怎么可能,因为我的新功能是 appdelegate 首先运行,其次我将如何在 viewcontroller 中使用我在 appdelegate 上获得的令牌和 udid 变量?

我的代码如下所示:

在 appdelegate.h 之前@interface

extern NSString *newDeviceToken;
extern NSString *udid;

在 appdelegate.m 之前@implementation

NSString *newDeviceToken;
NSString *udid;

在我的视图控制器中,我只需导入委托:

#import "AppDelegate.h"
4

2 回答 2

1

The delegate method:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

where you should get your variables, is run asynchronously. And yes, it might get called after your RootViewController has been initialized.

You shouldn't perform the URL connection on your ViewController, as you might not yet have an access token. You should perform this on the delegate method it self.

Now if you want to use a function of your ViewController and don't want to do the server communication in the AppDelegate, get a reference to your ViewController in your AppDelegate, make the URL function on your ViewController public, and call it.

As for getting a reference to your ViewController, this will be hard to answer, without knowing your App's design.

Assuming your App's RootViewController is a NavigationController and let's say the NavigationController RootViewController is named HomeNewViewController, this is how you would get a pointer reference to it from the App Delegate:

NavigationController *navigationController = (NavigationController*) [self.window rootViewController];

HomeNewViewController *homeController = (HomeNewViewController*)[navigationController.viewControllers objectAtIndex:0];

Then let's say in the HomeNewViewController, you have a function called uploadToken.

You could then do: [homeController uploadToken];

and upload it.

于 2013-03-25T10:38:45.590 回答
1

application:didRegisterForRemoteNotificationsWithDeviceToken调用后不会立即调用[UIApplication registerForRemoteNotificationTypes:]

这意味着您可以期望在加载视图时拥有令牌。将您的 UI 与连接代码分开。您的连接必须在application:didRegisterForRemoteNotificationsWithDeviceToken被调用时触发,而不是在视图控制器生命周期的某个时间点。请注意,在调用之前可能还会有一个对话框要求用户批准application:didRegisterForRemoteNotificationsWithDeviceToken

于 2013-03-25T10:39:49.027 回答