Swift - How to open specific view controller when push notification received?
When you app is in closed state you should check for launch option in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { }
and call your API.
Example:
if let option = launchOptions {
let info = option[UIApplicationLaunchOptionsKey.remoteNotification]
if (info != nil) {
goAnotherVC()
}
}
Open a ViewController from remote notification
I created a sample project with a local notification instead of a remote notification for ease of showing the functionality but it should be as simple as setting the root view controller of the window in the app delegate didreceiveremote notification.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Subscribe for notifications - assume the user chose yes for now
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil))
return true
}
func applicationDidEnterBackground(application: UIApplication) {
//Crete a local notification
let notification = UILocalNotification()
notification.alertBody = "This is a fake notification"
notification.fireDate = NSDate(timeIntervalSinceNow: 2)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let sb = UIStoryboard(name: "Main", bundle: nil)
let otherVC = sb.instantiateViewControllerWithIdentifier("otherVC") as! OtherViewController
window?.rootViewController = otherVC;
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
//Your code here
}
`
You need to worry about managing your view hierarchy and sending anything to it that you need to send from the notification user data.
In my example, I create a local notification when you close the app that fires after a view seconds. If you then launch the app from the notification, it will open the "other view controller" which would be the "SimplePostViewController" in your case.
Also, be sure that you are registering for remote notifications in the didFinishLaunchWithOptions.
Github very simple sample : https://github.com/spt131/exampleNotificationResponse
Open specific ViewController from push notification when application closed
If you want to open vc
from the closed state of your app, you can check if app was opened from click on Notification in this method of AppDelegate
.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
It looks like:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// When the app launch after user tap on notification (originally was not running / not in background)
if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
goToEventDetails(userInfo: launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any])
}
}
Where goToEventDetails
is method which instantiates VC and pushed id, and [UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any]
is content of Notification.
Open app in specific view when user taps on push notification with iOS 13 Swift 5
You can trigger a notification once you receive and the user clicks on the notification.
Along with the notification, you can pass the value which will later used to identify to which view controller you need to navigate.
Create a class which will be responsible for all the push notification navigation handling. You can name it like PushNotificationHandler. Let the PushNotificationHandler handler take care of all the logic to navigate to the view controllers.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
}
- Get the value from the deep link using the above delegate method
- Trigger a notification with the value
- Handle the notification inside PushNotificationHandler class
How to make your push notification Open a certain view controller?
You can detect if the app opened from the notification with this code in app delegate. You will need to set the initial view controller when the application state is UIApplicationStateInactive
before the app has become active. You can perform any logic there to decide which view controller should be opened and what content should be shown in that view controller.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
if(application.applicationState == UIApplicationStateActive) {
//app is currently active, can update badges count here
} else if(application.applicationState == UIApplicationStateBackground){
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
} else if(application.applicationState == UIApplicationStateInactive){
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
}
}
able redirect to specify view controller after clicked remote notification but only VC but without navigation bar
I think I understand the question to mean that you expect the view controller to appear in the context of a navigation controller that you have configured in storyboard. In that case, you'll need to do a little more to set things up:
find the navigation controller in your storyboard that contains the one with the "notice" ID, and give it a storyboard ID, too -- maybe something like "noticeNavigationController"
upon receiving the notification, build navigation controller from storyboard, too, and set it's root with the "notice" view controller that you know how to build...
// as you have it
UIStoryboard *mainsboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [mainsboard instantiateViewControllerWithIdentifier:@"notice"];
// but now build a navigation controller, too
UINavigationController *navVC = [mainsboard instantiateViewControllerWithIdentifier:@"noticeNavigationController"];
// make your vc the root
navVC.viewControllers = @[ vc ];
// and present** that navigation controller
[self.window.rootViewController presentViewController: navVC animated:YES completion:nil];
**Note, unless you're doing a presentation intentionally for some reason, it's more commonplace to just set the app's rootViewController to the navVC, rather than present it.
Related Topics
Urlcomponents Queryitems Losing Percent Encoding When Mutated
Update UIapplicationshortcutitem from Extension
The "Funk" Sound When Hitting Escape Key in App
How to Fill Triangle in Swift Using Core Graphics
Need Clarification on Typealias Syntax in Swift
Swift: Switch Statement Fallthrough Behavior
How to Find Multiple Nsrange for a String from Full String iOS Swift
Cannot Convert Value of Type 'Nsmutablearray' to Expected Argument Type '[Skaction]'
Swift Unsafemutablepointer & Unsafemutablepointer<Unsafepointer<Sometype>>
Automatically Reload Tableviewcontroller on Rewind
Trouble Calling a Method in an Init
Core Data with Swiftui Mvvm Feedback
Actions Assigned to Nsmenuitem Dont Seem to Work
List Is Not Conforming to Encodable
Bool.Hashvalue Valid to Convert to Int
Ambiguous Use of Recover Error While Using Promisekit
Swift Janus Can Not Publish Video, But Get Remote Video Successful - Can Not Know Reason