我的 App Delegate 中有一段代码通知我的第一个 View Controller 用户希望立即显示一些东西:
- (void)notifyAppWithURL:(NSURL *)url {
if(!url){
return;
}
NSDictionary *dict = [self parseQueryString:[url query]];
NSString *host = [url host];
[self notifyApp:host value:dict[@"id"]];
}
- (void)notifyApp:(NSString *)key value:(NSString *)value {
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[[NSNotificationCenter defaultCenter] postNotificationName:@"ShowOnLoad" object:nil userInfo:@{
key : value
}];
}
我从 didReceiveRemoteNotification
和 openURL
委托(delegate)方法中触发。这两者一切正常。
但是,似乎如果应用程序关闭,则调用此方法:
didFinishLaunchingWithOptions
和我发出相同的调用:
if(launchOptions[UIApplicationLaunchOptionsURLKey]){
[self notifyAppWithURL:launchOptions[UIApplicationLaunchOptionsURLKey]];
}
在内部,然后两个 NSNotification
被发送到 View Controller 。
两个问题:
如何解决在我的 App Delegate 中重复调用 notifyAppWithURL
的问题?
此外,是否有更好、更广泛的解决方案来处理来自用户的多个传入操作(然后触发其他一些操作)?
最佳答案
documentation for application:openURL:sourceApplication:annotation:
说如下:
If your app had to be launched to open the URL, the app calls the
application:willFinishLaunchingWithOptions:
andapplication:didFinishLaunchingWithOptions:
methods first, followed by this method.
您收到第一个通知是因为您在 application:didFinishLaunchingWithOptions:
中调用了 notifyAppWithURL:
,而第二个通知是因为您在 application:openURL: 中调用了它源应用程序:注释:
。一个简单的解决方案是简单地删除 application:didFinishLaunchingWithOptions:
中的调用。
就您的第二个问题而言,并没有真正通用的方法来处理导致某些代码运行两次或更多次的多个操作。 dispatch_once
是确保一段代码在整个过程中只运行一次且仅运行一次的标准方法,但这显然不是您想要的。
关于ios - 避免在 App Delegate 中重复执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301090/