在我的应用中,我会在用户执行某项操作后推送本地通知 当用户从推送通知中打开应用程序时,我想将一个事件注册到跟踪系统(在我的情况下是 Mixpanel )。 我应该有一个密钥来注册我从服务器上获取此事件的事件。
所以我想做的是在函数中获取密钥,在此函数完成后,我想注册该事件。
我尝试了performSelectorOnMainThread:withObject:waitUntilDone:
,但它无效
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//some code here
[self performSelectorOnMainThread:@selector(performHandShake)
withObject:nil
waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(registerLaunchOptionsDetails:)
withObject:launchOptions
waitUntilDone:YES];
//some code here
}
-(void)performHandShake
{
//myParams here
[[RKClient sharedClient] get:@"/handshake" usingBlock:^(RKRequest *request) {
request.params = [RKParams paramsWithDictionary:myParams];
request.method = RKRequestMethodGET;
request.onDidLoadResponse = ^(RKResponse *response) {
//Set the tracking key here
};
request.onDidFailLoadWithError = ^(NSError *error) {
NSLog(@"ERROR:%@",error);
};
}];
}
-(void)registerLaunchOptionsDetails:(NSDictionary *)launchOptions
{
UILocalNotification *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
//Register the event here using the key
}
}
问题是在registerLaunchOptionsDetails
完成之前执行的performHandShake
功能且事件未被注册。
答案 0 :(得分:1)
对于您想要做的事情可能有点过分,但是有一个类似于节点的异步的库。您可以将异步任务链接在一起和/或等到多个完成后再执行其他操作。
答案 1 :(得分:1)
执行-[RKClient get:usingBlock]
时,它将创建一个将在后台执行的网络操作,该方法将返回。
这将清除registerLaunchOptionsDetails
运行的路径,这将在网络操作完成之前发生。
当网络操作成功完成并且您拥有所请求的数据时,request.onDidLoad
将运行。这就是调用registerLaunchOptionsDetails:
的原因。
答案 2 :(得分:1)
我们会在您需要时调用阻止request.onDidLoadResponse
,因此您需要从此阻止中调用registerLaunchOptionsDetails:
。不要忘记通过launchOptions
将performHandShake
传递给此块并创建对self
的弱引用,以防止它在块中保留。
最终代码应该是这样的:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//some code here
[self performSelectorOnMainThread:@selector(performHandShake:) withObject:launchOptions waitUntilDone:YES];
//some code here
}
-(void)performHandShake:(NSDictionary *)launchOptions
{
//myParams here
[[RKClient sharedClient] get:@"/handshake" usingBlock:^(RKRequest *request){
request.params = [RKParams paramsWithDictionary:myParams];
request.method = RKRequestMethodGET;
__weak AppDelegate *weakSelf = self;
request.onDidLoadResponse = ^(RKResponse *response)
{
//Set the tracking key here
// Here is registerLaunchOptionsDetails: call
[weakSelf registerLaunchOptionsDetails:launchOptions];
};
request.onDidFailLoadWithError = ^(NSError *error)
{
NSLog(@"ERROR:%@",error);
};
}];
}
-(void)registerLaunchOptionsDetails:(NSDictionary *)launchOptions
{
UILocalNotification *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification)
{
//Register the event here using the key
}
}