Making a new view controller appear after interstitial ad is dismissed - swift

I am building an iOS app in swift with Xcode that has a button that, when pressed, will (among other things) show an interstitial Admob ad, and then go to a different view controller. Right now, when I press the button, an interstitial ad will appear. However, when I close the ad, the view is still on the original page. If I click the button again, then I am taken to the second view controller. Sometimes, however, I have to dismiss three or four ads before I get to the second view controller. How can I make it so that, after I dismiss the interstitial ad, I go straight to the second view controller?
Here is the current code:
#IBAction func postPressed(_ sender: Any) {
if contact.text?.isEmpty == true {
print("No contact")
return
}
if avail.text?.isEmpty == true {
print("No availability")
return
}
uploadSpot()
}
func uploadSpot() {
let key = Int.random(in: 20001..<30000)
let object: [String: Any] = [
"Contact": contact.text!,
"Availability": avail.text!,
]
geoFireRef.child("\(key)").setValue(object)
let location = manager.location!
geoFire.setLocation(location, forKey: "\(key)")
if interstitialAd?.isReady == true {
interstitialAd?.present(fromRootViewController: self)
}
let storyboard = UIStoryboard(name: "SpotLoaded", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "SpotLoaded")
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true)
}
The import part is in the function "uploadSpot()," where
if interstitialAd?.isReady == true {
interstitialAd?.present(fromRootViewController: self)
}
presents the ad and
let storyboard = UIStoryboard(name: "SpotLoaded", bundle: nil)
let vc = storyboard.instantiateViewController(identifier: "SpotLoaded")
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true)
switches the viewcontroller. I have tried reversing the order if these two (i.e. putting let storyboard, etc., before if insterstitialAd), but that just takes me to the new view controller and the ad never appears. I have also tried putting the let storyboard chunk inside of the brackets following the if interstitialAd. This does not help either. If I put it after interstitialAd?.present(fromRootViewController: self), I have the same problem where the ad shows but the view controller does not change. If I put it after, the viewcontroller changes but the ad never shows.
As the main purpose of interstitial ads is to appear in between views of an app, I do not think what I am trying to do should be so difficult. I think there must just be something I am missing or do not understand. Please help in whatever way you can.

Related

Open first View based on condition

I want my app to check at start conditionaly if a variable is correct or not. Based on that it should either go to an intro screen (where he can select a variable in my case select a team) or it should start the main view. After searching i found this code and edited it.
But there still seems to be problems. First of all I dont have two identifier. The Intro has one but not the main view. My main View is called WeatherViewController and the Intro screen is called FirstScreenViewController.
I also added a picture of my Main.storyboard.
I also googled a lot about conditional UINavigationController but I can only understand with a video and did not found a video about it.
I tried to use the code from here.
var id = hello ? "goToIntro" : "???"
self.window = UIWindow(frame: UIScreen.main.bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let WeatherViewController: UIViewController = mainStoryboard.FirstScreenViewController(withIdentifier: WVC has no identifier??) as UIViewController
self.window?.rootViewController = WeatherViewController
self.window?.makeKeyAndVisible()
if hello {
self.performSegue(withIdentifier: "goToIntro", sender: self)
} else {
/here nothing should happen. It should open the Main View
self.performSegue(withIdentifier: "???", sender: self)
}
Simply repeat the steps you did for creating the segue goToIntro.
Add a new UIViewController (MainViewController) in your storyboard.
Add a segue and give it an identifier.
Provide the identifier value in the else condition of the code that you've shown in your post to perform the segue to the UIViewController that you've just created.
The final code should look something like this:
var id = hello ? "goToIntro" : "goToMain"
guard let windowScene = scene as? UIWindowScene else { return }
window = UIWindow(windowScene: windowScene)
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let weatherViewController = mainStoryboard.instantiateInitialViewController()
window?.rootViewController = weatherViewController
window?.makeKeyAndVisible()
weatherViewController.performSegue(withIdentifier: id, sender: self)
You don't need the if else block since the id is already determined using the ? ternary operator.

Remove a ViewController from navigationStack and add a new instance of it

I have a SongNamesViewController with navigationController embedded. When a song is chosen from a list I open PlaySongViewController and add to the navigationController using following function:
func openPlaySongViewController() {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let playSongViewController = storyBoard.instantiateViewController(withIdentifier: "playSongViewController")
self.navigationController?.pushViewController(playSongViewController, animated: true)
}
Now, a message arrives via remote push-notification. The user taps on the push-notification icon and then I display the song using "openPlaySongViewController()" function. If another push-notification comes and then I display another PlaySongViewController on top of existing PlaySongViewController.
Current flow: (NavigationController)->SongNamesViewController>PlaySongViewController->PlaySongViewController
How do I remove the existing PlaySongViewController that is on the navigationController before adding a new instance of PlaySongViewController?
I tried the following but the PlaySongViewController that is on navigationController does not go away.
for viewController in self.navigationController!.viewControllers {
if viewController.isKind(of: PlaySongViewController.self) {
viewController.removeFromParent()
}
}
topViewController returns what is on top of the navigation stack. So you should pop it if needed.
func removeLastControllerIfNeeded() {
guard navigationController?.topViewController is PlaySongViewController else { return }
navigationController?.popViewController(animated: true)
}

Instantiating deep View Controller with Tab bar and Navigation

I am using Xcode 11 and Swift 5.
Upon receiving an APNS notification, I need to jump to a view controller deep in my storyboard from AppDelegate. This viewController (chatVC) is behind a tabbar and a navigation controller and several other view controllers. See the image below. I know how to check the notification for tags and how to use launchOptions in AppDelegate to trigger the jump. But I am struggling with how to establish the context for that last view controller so that the user can use the back button all the way back to the tab bar controller.
I have read many SO answers, and tried many approaches but none seem to have the same embedding of a nav controller inside a tab bar controller. Here is my code in AppDelegate (after reading the tag in the notification):
if tag == "CS" {
// Set up a Chat View Controller.
if let chatVC = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: Constants.Storyboard.chatVC) as? NewChatViewController,
let tabBarVC = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: Constants.Storyboard.tabBarController) as? UITabBarController,
let csVC = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: Constants.Storyboard.csViewController) as? CustomerServiceViewController,
let helpVC = UIStoryboard(name:"Main", bundle: .main).instantiateViewController(withIdentifier: Constants.Storyboard.helpVC) as? HelpViewController
{
// Set the customer service document Id.
chatVC.cs = cs
// Make the tabBarVC the Root View Controller
self.window?.rootViewController = tabBarVC
self.window?.makeKeyAndVisible()
// Select the Favorites Index.
tabBarVC.selectedIndex = 0
// Push the Customer Service VC on top.
tabBarVC.show(csVC, sender: Any?.self)
// Push the Help VC on top of Customer Service VC.
csVC.show(helpVC, sender: Any?.self)
// Push the the chat detail page on top.
helpVC.show(chatVC, sender: Any?.self)
}
}
}
return true
What can I do to jump to the chatVC and set up the navigation context beneath it so the back button can be used?
Here is how you can do it:
guard let tabBarVC = UIApplication.shared.windows.filter( {$0.rootViewController is UITabBarController } ).first?.rootViewController as? UITabBarController else { return }
tabBarVC.selectedIndex = 0 //you can select another tab if needed
guard let chatVC = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: Constants.Storyboard.chatVC) as? NewChatViewController else { return }
if let navController = tabBarVC.viewControllers?[0] as? UINavigationController {
navController.pushViewController(chatVC, animated: true)
}
You can also pass objects from your notification to your chatVC here before pushing it, in case you need to do that.
Hope this works for you!

Swift viewWillAppear redirect

I'm using "viewWillAppear" to check UserDefaults.standard if i have data on the defaults i want redirect to Dashboard View and pass out of Login.
When i Log In correctly the app redirect normally but not in viewWillAppear in case of have data.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let defaults = UserDefaults.standard
if defaults.string(forKey: "username") != nil {
print("Exist")
print(defaults.string(forKey: "username")!)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Dashboard")
self.present(vc, animated: true, completion: nil)
}
}
And i get this error con debug.
2016-11-04 17:44:32.130024 RHiOS[1155:278240] Warning: Attempt to present <RHiOS.MenuViewController: 0x100f0d480> on <RHiOS.ViewController: 0x100e0b880> whose view is not in the window hierarchy!
How can i redirect to Dash in case of have data? Thanks.
You cannot present a ViewController in viewWillAppear. Simply put this code in viewDidAppear and it should fix your problem.
When the view is not visible, it's not in the window hierarchy as the error mentioned. You could also create a segue in your storyboard and call performSegue(withIdentifier:sender:) instead.
You won't be able to present anything when the view hasn't appeared yet, so you either have to move your code into viewDidAppear or prevent this view from showing in the first place and redirect directly to the dashboard from a parent view controller that presents either the dashboard or login screen depending on whether or not you have data.

Attempt to present * whose view is not in the window hierarchy

I am using the following code in AppDelegate to display a popup window within the app when a button is selected, i will eventually move this to a label hyperlink but just testing currently.
let storyboard = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("test") as! ViewController
let popOverVC = UIStoryboard(name:"Main", bundle: nil).instantiateViewControllerWithIdentifier("sbPopUpID") as! PopUpViewController
storyboard.addChildViewController(popOverVC)
popOverVC.view.frame = storyboard.view.frame
storyboard.view.addSubview(popOverVC.view)
popOverVC.didMoveToParentViewController(storyboard)
self.window?.rootViewController?.presentViewController(storyboard, animated: true, completion: nil)
The first time i select a button this works correctly, however on all subsequent button presses the following error is displayed.
2016-10-28 11:27:40.551 testfordeeplinks[20496:104536] Warning:
Attempt to present
on whose view is not
in the window hierarchy!
For anyone who stumbles across this in the future, this is how i resolved;
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window?.rootViewController = storyboard
rootViewController doesn't necessarily refer to the view controller that is currently visible. For example, if you utilise a UINavigationController, rootViewController will hold a reference to that navigation controller which in itself is buried deep in the view hierarchy and hence when you try to present a view controller on it get an error. What I would recommend doing is grabbing the last view controller in navController.viewControllers and presenting your popup on that. See the following code:
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
if let navController = appDel.keyWindow?.rootViewController as? UINavigationController {
if let visibleVC = navController.viewControllers.last {
visibleVC.presentViewController(storyboard, animated: true, completion: nil)
}
}
Give that a try and let me know. :)