Push Notification -didFinishLaunchingWithOptions
Когда я отправляю push-уведомление, и мое приложение открыто или в фоновом режиме, и я нажимаю на push-уведомление, мое приложение перенаправляет на PushMessagesVc
viewController
(по назначению)
Для этого я использую следующий код:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
PushMessagesVc *pvc = [mainstoryboard instantiateViewControllerWithIdentifier:@"PushMessagesVc"];
[self.window.rootViewController presentViewController:pvc
animated:YES
completion:NULL];
}
В приведенном выше коде/сценарии нет проблем, но если приложение закрыто и я нажимаю push-уведомление, приложение не перенаправляет мой PushMessagesVc
viewController
в этом случае, и приложение остается на главном экране.
Для второго сценария я использую следующий код:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
sleep(1);
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeNone)];
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
NSDictionary *userInfo = [launchOptions valueForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
if(apsInfo) {
UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
PushMessagesVc* pvc = [mainstoryboard instantiateViewControllerWithIdentifier:@"PushMessagesVc"];
[self.window.rootViewController presentViewController:pvc animated:YES completion:NULL];
return YES;
}
return YES;
}
Но в этом случае PushMessagesVc
не появляется.
Ответы
Ответ 1
Поскольку вы хотите представить viewController
при получении Push Notification, вы можете попробовать использовать NSNotificationCenter
для своих целей:
Часть 1: настройте класс (в вашем случае, rootViewController
) для прослушивания/ответа на NSNotification
Предположим, MainMenuViewController
является rootViewController
вашего navigationController
.
Настройте этот класс, чтобы прослушать 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];
}
Часть 2: Почтовое уведомление (возможно из любого места вашего кода)
В вашем случае методы AppDelegate.m должны выглядеть так:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//firstly, don't sleep the thread, it 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: Я еще не сделал этого для своих проектов (но пока), но он работает, и это лучший способ, которым я мог бы думать о том, чтобы делать этот материал (на данный момент)
Ответ 2
Swift 2.0
Для состояния "Не работает" (локальное и удаленное уведомление)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Handle notification
if (launchOptions != nil) {
// For local Notification
if let localNotificationInfo = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
if let something = localNotificationInfo.userInfo!["yourKey"] as? String {
self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
}
} else
// For remote Notification
if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as! [NSObject : AnyObject]? {
if let something = remoteNotification["yourKey"] as? String {
self.window!.rootViewController = UINavigationController(rootViewController: YourController(yourMember: something))
}
}
}
return true
}
Ответ 3
Swift 5
Чтобы получить словарь push-уведомлений в didFinishLaunchingWithOptions, когда приложение завершается, получаются push-уведомления и пользователь нажимает на этот
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: AnyObject] {
if let aps1 = userInfo["aps"] as? NSDictionary {
print(aps1)
}
}
return true
}
толчок уведомления словарь будет отображаться в предупреждении.
Ответ 4
Быстрая версия:
if let localNotification: UILocalNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { //launchOptions is not nil
self.application(application, didReceiveLocalNotification: localNotification)
}