更新时间:2023-02-16 21:49:40
由于您只想在收到推送通知时呈现一个 viewController
,您可以尝试使用 NSNotificationCenter
> 为您的目的:
Since you only want to present a viewController
when you get a Push Notification, you may try utilizing NSNotificationCenter
for your purposes:
假设,MainMenuViewController
是 navigationController
的 rootViewController
.
设置这个类来监听NSNotification
:
- (void)viewDidLoad {
//...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(presentMyViewOnPushNotification)
name:@"HAS_PUSH_NOTIFICATION"
object:nil];
}
-(void)presentMyViewOnPushNotification {
//The following code is no longer in AppDelegate
//it should be in the rootViewController class (or wherever you want)
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
PushMessagesVc *pvc = [mainstoryboard instantiateViewControllerWithIdentifier:@"PushMessagesVc"];
[self presentViewController:pvc animated:YES completion:nil];
//either presentViewController (above) or pushViewController (below)
//[self.navigationController pushViewController:pvc animated:YES];
}
在您的情况下,AppDelegate.m 方法应该看起来像:
In your case, AppDelegate.m methods should look like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//firstly, don't sleep the thread, it's pointless
//sleep(1); //remove this line
if (launchOptions) { //launchOptions is not nil
NSDictionary *userInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
if (apsInfo) { //apsInfo is not nil
[self performSelector:@selector(postNotificationToPresentPushMessagesVC)
withObject:nil
afterDelay:1];
}
}
return YES;
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//this method can be done using the notification as well
[self postNotificationToPresentPushMessagesVC];
}
-(void)postNotificationToPresentPushMessagesVC {
[[NSNotificationCenter defaultCenter] postNotificationName:@"HAS_PUSH_NOTIFICATION" object:nil];
}
PS:我还没有为我的项目做过这个(还),但它确实有效,而且是我能想到的***的方式来做这种事情(目前>)
PS: I haven't done this for my projects (yet) but it works and is the best way i could think of doing this kinda stuff (for the moment)