Push-уведомление -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
не появляются.
4 ответа
Так как вы хотите только представить viewController
когда вы получаете Push-уведомление, вы можете попробовать использовать 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: Post Notification (возможно из любого места в вашем коде)
В вашем случае методы AppDelegate.m должны выглядеть так:
- (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: я еще не сделал этого для своих проектов (пока), но это работает, и это лучший способ, который я мог придумать, чтобы делать подобные вещи (на данный момент)
Swift 3 Для получения словаря push-уведомлений в didFinishLaunchingWithOptions, когда приложение завершает работу и получает push-уведомления и пользователь нажимает на них
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject] {
if let aps1 = userInfo["aps"] as? NSDictionary {
print(aps1)
}
}
return true
}
Толчок уведомления словарь будет отображаться в предупреждении.
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
}
Swift 5
Я пишу свое уведомление в var "notification" в didFinishLaunchingWithOptions, и если "notification"!= Nil запустил мой push в applicationDidBecomeActive, после этого удалил его ( = nil)
class AppDelegate: UIResponder, UIApplicationDelegate {
var notification: [AnyHashable : Any]? = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
registerForPushNotifications()
//write notification to var
if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
self.notification = launchOptions![UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable : Any]
}
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
if notification != nil {
//for launch notification after terminate app
NotificationCenter.default.post(name: Notification.Name(rawValue: "startPush"), object: nil)
notification = nil
}
}
Swift версия:
if let localNotification: UILocalNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { //launchOptions is not nil
self.application(application, didReceiveLocalNotification: localNotification)
}