ios - Change tabs and open modal window dynamically - ios

I have an app that sends local notiffications at specific times. When the user taps on the notification, the app should open on a particular tab (a library tab) and then open automatically one of the lessons (without the user having to tap on it).
I can get the app to switch to the Library tab, but the modal with the lesson never appears.
This is the code I'm using:
if let tabBarController = window.rootViewController as? UITabBarController {
// this works
tabBarController.selectedViewController!.dismiss(animated: true, completion: nil)
tabBarController.selectedViewController = tabBarController.viewControllers?[1]
// Segue to particular lesson
let vc = tabBarController.selectedViewController as? LibraryViewController
let lessonVC = LessonViewController()
let les60 = Lesson(lessonNumber: "60")
lessonVC.delegate = vc
lessonVC.lesson = les60
vc?.present(UINavigationController(rootViewController: lessonVC), animated: true)
}
This is the code I use for every item in the Library:
let lessonVC = LessonViewController()
lessonVC.delegate = self
lessonVC.lesson = lessonsArray[indexPath.row]
present(UINavigationController(rootViewController: lessonVC), animated: true)
so I tried to replicate it above but it does not work.

Related

AppDelegate presents views twice

I'm implementing quick-actions for my app and for that I need to present viewcontrollers from the app delegate. I use code like this:
let viewController = storyboard.instantiateViewController(withIdentifier :"MyControllerID") as! MyController
let navController = UINavigationController.init(rootViewController: viewController)
if let window = self.window, let rootViewController = window.rootViewController {
var currentController = rootViewController
while let presentedController = currentController.presentedViewController {
currentController = presentedController
}
currentController.present(navController, animated: true, completion: nil)
}
If the app is in background and the quickaction is clicked everything works fine, but if the app hasn't been started yet and the quick-action gets clicked the view is presented twice.
What am I doing wrong here?
// Edit 1: This code is in a function and the function is called in applicationDidBecomeActive
In didFinishLaunchingWithOptions I check if the app was launched via Quick-Actions like this:
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
launchedShortcutItem = shortcutItem
}
The launchedShortcutItem is a variable:
var launchedShortcutItem: UIApplicationShortcutItem?
// Edit 2: For those who don't know what I mean by "Quick-Actions" here are the Apple Pages for them: Guideline, Documentation

Opening ViewController In AppDelegate While Keeping Tabbar

In my Xcode project when a user taps on a notification I want to first send them to a certain item in my tabBar then I want to instantiate a view controller and send an object over to that view controller. I have code the that sends them to the tabBar I want, but I do not know how to instantiate them to the view controller while keeping the tabBar and navigation bar connected to the view controller. All the answers on this require you to change the root view controller and that makes me lose connection to my tabBar and navigation bar when the view controller is called.
A Real Life Example of this: User receives Instagram notification saying "John started following you" -> user taps on notification -> Instagram opens and shows notifications tab -> quickly send user to "John" profile and when the user presses the back button, it sends them back to the notification tab
Should know: The reason why I'm going to a certain tab first is to get that tab's navigation controller because the view controller I'm going to does not have one.
Here's my working code on sending the user to "notifications" tab (I added comments to act like the Instagram example for better understanding):
if let tabbarController = self.window!.rootViewController as? UITabBarController {
tabbarController.selectedViewController = tabbarController.viewControllers?[3] //goes to notifications tab
if type == "follow" { //someone started following current user
//send to user's profile and send the user's id so the app can find all the information of the user
}
}
First of all, you'll to insatiate a TabBarController:
let storyboard = UIStoryboard.init(name: "YourStoryboardName", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "YourTabBarController") as! UITabBarController
And then insatiate all of the viewControllers of TabBarController. If your viewControllers is embedded in to the UINavigationController? If so, you'll to insatiate a Navigation Controller instead:
let first = storyboard.instantiateViewiController(withIdentifier: "YourFirstNavigationController") as! UINavigationController
let second = storyboard.instantiateViewiController(withIdentifier: "YourSecondNavigationController") as! UINavigationController
let third = storyboard.instantiateViewiController(withIdentifier: "YourThirdNavigationController") as! UINavigationController
Also you should instantiate your desired ViewController too:
let desiredVC = storyboard.instantiateViewController(withIdentifier: "desiredVC") as! ExampleDesiredViewController
Make all of the NavigationControllers as viewControllers of TabBarController:
tabBarController.viewControllers = [first, second, third]
And check: It's about your choice.
if tabBarController.selectedViewController == first {
// Option 1: If you want to present
first.present(desiredVC, animated: true, completion: nil)
// Option 2: If you want to push
first.pushViewController(desiredVC, animated. true)
}
Make tabBarController as a rootViewController:
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
Finally: It's your completed code:
func openViewController() {
let storyboard = UIStoryboard.init(name: "YourStoryboardName", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "YourTabBarController") as! UITabBarController
let first = storyboard.instantiateViewiController(withIdentifier: "YourFirstNavigationController") as! UINavigationController
let second = storyboard.instantiateViewiController(withIdentifier: "YourSecondNavigationController") as! UINavigationController
let third = storyboard.instantiateViewiController(withIdentifier: "YourThirdNavigationController") as! UINavigationController
let desiredVC = storyboard.instantiateViewController(withIdentifier: "desiredVC") as! ExampleDesiredViewController
tabBarController.viewControllers = [first, second, third]
if tabBarController.selectedViewController == first {
// Option 1: If you want to present
first.present(desiredVC, animated: true, completion: nil)
// Option 2: If you want to push
first.pushViewController(desiredVC, animated. true)
}
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
}
If you want to present or push ViewController when the notification is tapped? Try something like that:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
openViewController()
completionHandler()
default:
break;
}
}
}
I can think of two ways to do that:
1) If that view controller is a UINavigationController you can simply push the profile from wherever you are:
if let tabNavigationController = tabbarController.viewControllers?[3] as? UINavigationController {
tabbarController.selectedViewController = tabNavigationController
let profileViewController = ProfileViewController(...)
// ... set up the profile by setting the user id or whatever you need to do ...
tabNavigationController.push(profileViewController, animated: true) // animated or not, your choice ;)
}
2) Alternatively, what I like to do is control such things directly from my view controller subclass (in this case, PostListViewController). I have this helper method in a swift file that I include in all of my projects:
extension UIViewController {
var containedViewController: UIViewController {
if let navController = self as? UINavigationController, let first = navController.viewControllers.first {
return first
}
return self
}
}
Then I would do this to push the new view controller:
if let tabViewController = tabbarController.selectedViewController {
tabbarController.selectedViewController = tabViewController
if let postListViewController = tabViewController.containedViewController as? PostListViewController {
postListViewController.goToProfile(for: user) // you need to get the user reference from somewhere first
}
}
In my last live project, I'm using the same approach like yours. So even though I doubt this method is the correct or ideal for handling a push notification from the AppDelegate (I still got a lot of stuff to learn in iOS 🙂), I'm still sharing it because it worked for me and well I believe the code is still readable and quite clean.
The key is to know the levels or stacks of your screens. The what are childViewControllers, the topMost screen, the one the is in the bottom, etc...
Then if you're now ready to push to a certain screen, you would need of course the navigationController of the current screen you're in.
For instance, this code block is from my project's AppDelegate:
func handleDeeplinkedJobId(_ jobIdInt: Int) {
// Check if user is in Auth or in Jobs
if let currentRootViewController = UIApplication.shared.keyWindow!.rootViewController,
let presentedViewController = currentRootViewController.presentedViewController {
if presentedViewController is BaseTabBarController {
if let baseTabBarController = presentedViewController as? BaseTabBarController,
let tabIndex = TabIndex(rawValue: baseTabBarController.selectedIndex) {
switch tabIndex {
case .jobsTab:
....
....
if let jobsTabNavCon = baseTabBarController.viewControllers?.first,
let firstScreen = jobsTabNavCon.childViewControllers.first,
let topMostScreen = jobsTabNavCon.childViewControllers.last {
...
...
So as you can see, I know the hierarchy of the screens, and by using this knowledge as well as some patience in checking if I'm in the right screen by using breakpoints and printobject (po), I get the correct reference. Lastly, in the code above, I have the topMostScreen reference, and I can use that screen's navigationController to push to a new screen if I want to.
Hope this helps!

3D Touch Quick Action launches black screen. UiNavigationController->UITableViewController-> UIViewController

The app that I am working on has a UITableViewController embedded in a UINavigationController. Tapping on cells in the UITableViewController presents other UIViewControllers. I am trying to implement 3D touch in an iOS app so that the user can directly access one of the UIViewControllers from the home screen. Everything works fine except that when I tap on the link on the home screen, I get a black screen (except for the navigation bar). Here is the relevant code from the AppDelegate:
func handleShortCutItem(shortcutItem: UIApplicationShortcutItem) -> Bool {
var handled = false
guard ShortcutIdentifier(fullType: shortcutItem.type) != nil else { return false }
guard let shortCutType = shortcutItem.type as String? else { return false }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc = UIViewController()
switch (shortCutType) {
case ShortcutIdentifier.Tables.type:
vc = storyboard.instantiateViewController(withIdentifier: "TableVC") as! StatTableViewController
handled = true
break
case ShortcutIdentifier.ChiSquare.type:
vc = storyboard.instantiateViewController(withIdentifier: "Chisquare") as! CSViewController
handled = true
break
case ShortcutIdentifier.PowerContinuous.type:
vc = storyboard.instantiateViewController(withIdentifier: "PowerCont") as! PowerContViewController
handled = true
break
case ShortcutIdentifier.PowerDichotomous.type:
vc = storyboard.instantiateViewController(withIdentifier: "PowerDichot") as! PowerDichotViewController
handled = true
break
default:
break
}
let navVC = self.window?.rootViewController as! UINavigationController
navVC.pushViewController(vc, animated: true)
// navVC.show(vc, sender: self) // Same result
return handled
}
I'm reasonably sure that I'm getting to the correct UIViewController each time, but the screen is black. I can navigate back to the UITableViewController, where I can then segue back to the UIViewController and it works just fine. So it is clearly something in the presentation of the window that is messed up.
Thanks in advance for any and all advice.
The problem turned out to be in my info.plist file. I had mistakenly thought that $(PRODUCT_BUNDLE_IDENTIFIER) as a prefix for the UIApplicationShortcutItemType would be my bundle identifier. It wasn't, so replacing $(PRODUCT_BUNDLE_IDENTIFIER) with my explicit bundle identifier did the trick.
Thanks for the comments, which eventually led to my finding the answer.

Change order in Navigation Controller

I'm working with Swift3. I have an App with the VCs as in the picture.
In the Mainmenu-VC the user triggers the Input-segue. User enters a firstname in the Input-VC. This triggers the Select-segue to Select-VC to select a surname and trigger Selected-segue to Details-VC.
From the Mainmenu-VC the user can also access the Details-VC. Back via NavigationControllerMechanism to Mainmenu-VC.
I want to change the NavigationControllerMechanism 'history', so that when the user enters from the Details-VC via the Selected-segue, the previous VC is changed from Select-VC to Mainmenu-VC.
So basically when in the Details-VC, the Back always returns to Mainmenu-VC.
I have tried combining various solutions from the web, without succes.
Is this possible?
Yes it is.
The View-Controller stack is stored in currentViewController.navigationController?.viewControllers.
So you should make something like :
//In Your Details VC :
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let stack = self.navigationController?.viewControllers else { return }
//get the mainMenu VC
let mainVC = stack.first!
// Rearrange your stack
self.navigationController?.viewControllers = [mainVC, self]
//Now you can press "bac" to Main VC
}
you want to change navigation stack in this way you can manipulate
let myprofile = storyboard.instantiateViewController(withIdentifier: "Profile1ViewController") as! Profile1ViewController
let sourseStack = self.navigationController!.viewControllers[0];
var controllerStack = self.navigationController?.viewControllers
let index = controllerStack!.index(of: sourseStack);
controllerStack![index!] = myprofile
self.navigationController!.setViewControllers(controllerStack!, animated: false);
to go to RootViewController
dispatch_async(dispatch_get_main_queue(), {
self.navigationController?.popToRootViewControllerAnimated(true)
})

Welcome Screen on Launch

I want a way for the user to have a welcome screen / tutorial on the first launch of the app. If it isn't the first launch of the app, then it open as it usually would.
I already have the welcome screen tied to a button function if the app opens normally. I'm using BWWalkThroughViewController. Here's my code for the button function:
#IBAction func showWalkThroughButtonPressed() {
// Get view controllers and build the walkthrough
let stb = UIStoryboard(name: "MainStoryboard", bundle: nil)
let walkthrough = stb.instantiateViewControllerWithIdentifier("walk0") as! BWWalkthroughViewController
let page_one = stb.instantiateViewControllerWithIdentifier("walk1") as UIViewController
let page_two = stb.instantiateViewControllerWithIdentifier("walk2") as UIViewController
let page_three = stb.instantiateViewControllerWithIdentifier("walk3") as UIViewController
let page_four = stb.instantiateViewControllerWithIdentifier("walk4") as UIViewController
let page_five = stb.instantiateViewControllerWithIdentifier("walk5") as UIViewController
// Attach the pages to the master
walkthrough.delegate = self
walkthrough.addViewController(page_one)
walkthrough.addViewController(page_two)
walkthrough.addViewController(page_three)
walkthrough.addViewController(page_four)
walkthrough.addViewController(page_five)
self.presentViewController(walkthrough, animated: true, completion: nil)
}
func walkthroughCloseButtonPressed() {
self.dismissViewControllerAnimated(true, completion: nil)
}
That code is located in the MyTableViewController.swift file.
Here's what I can't figure out:
I want the view controllers to show on first launch. Once the user finishes the tutorial, they can press the Close button and it will close. I have the code to check if it's the app's first launch. It's located in the AppDelegate.swift file. Here's that code:
// First Launch Check
let notFirstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
if notFirstLaunch {
print("First launch, setting NSUserDefault")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
}
else {
print("Not first launch.")
}
return true
So how do I get the welcome screen to launch on first launch? Do I have to create a function in AppDelegate to handle that, and if so what do I have to do to make the tutorial the initial view controller for just the first launch?
I believe what you need to do is already covered here: Programmatically set the initial view controller using Storyboards. If that doesn't work for you add more notes on why the implementation failed. A google search on "programatically change uiviewcontroller on launch ios" will yield other similar links.

Resources