Tab Controller is dismissing as well when GADRewardBasedVideoAd in AdMob dismisses - ios

I have an ViewController with GADRewardBasedVideoAd.
I can easily play and close ads, but with the ad closes ViewController as well.
What can I do?
#IBAction func ad_button_click(_ sender: Any) {
if GADRewardBasedVideoAd.sharedInstance().isReady == true
{
GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self)
}
}

For those of you who is facing the the same issue:
You can create a new class for your rootViewController (TabBarController or NavigationController etc.) and implement there something like that:
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismissalCounter += 1
if (dismissalCounter < 2) {
super.dismiss(animated: flag, completion: completion)
}
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
dismissalCounter = 0
}
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
dismissalCounter = 0
super.present(viewControllerToPresent, animated: flag, completion: completion)
}
var dismissalCounter : Int = 0
Important! Use this functions inside TabBarController or NavigationController, otherwise it is not gonna work
UPD:
In my case unfortunatly it breaks all NavigationControllers inside a TabBarController (titles don't show and there are no buttons inside them), if I will figure fix actions, I'll let you know
UPD2:
Pretty obvious decision will be to change the initialViewController and view add from it, it'll not be dismissed
UPD3:
I solved this very and very strange:
class ViewController : UIViewController {
override func viewWillAppear(_ animated: Bool) {
if GADRewardBasedVideoAd.sharedInstance().isReady == false {
let request = GADRequest()
rewardBasedVideo!.load(request, withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
}
}
var rewardBasedVideo: GADRewardBasedVideoAd?
#IBAction func ad_button_click(_ sender: Any) {
if rewardBasedVideo!.isReady == true {
let bl = blur()
self.present(bl, animated: true, completion: {
self.rewardBasedVideo?.present(fromRootViewController: bl)
})
}
}
}
class blur : UIViewController {
override func viewDidLoad() {
checkForKeyWindow()
}
func checkForKeyWindow() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
if (UIApplication.topViewController() == self) {
print("dismissed and forgotten")
self.dismiss(animated: true, completion: nil)
} else {
print("not keywindow")
self.checkForKeyWindow()
}
})
}
#objc func close() {
self.dismiss(animated: true, completion: nil)
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController, top.view.window != nil {
return topViewController(base: top)
} else if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}

Related

How to reload present view controller swift?

I have two Present view controllers. The thing i want to do is when the second Present view controller is dismissed it will automatically reload the first present view controller(Table view). note: first view controller holds a table view, basically i want to reload the table view of first controller.
ViewWillAppear code:
override func viewWillAppear(_ animated: Bool) {
tableViewReloadFromCreateProductVC()
}
func tableViewReloadFromCreateProductVC () {
tableView.reloadData()
}
Calling from second view controller code:
SecondViewController.tableViewReloadFromCreateProductVC()
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
FirstViewController calling 2nd view controller
#IBAction func CallSecondViewButton(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
}
just write the code in viewWillAppear() method of the view controller that you want to reload like this
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
//perform api call if any
yourTableView.reloadData()
}
2nd view controller
#IBAction func CloseButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
after dissmissing the viewWillAppear method of firstViewController will autometically called.
The First two snippets are for first view controller and the last one is for second view controller
Reloading the entire table view could sometimes be costly and it also sounds like you're making an API call as well so unless you want your table view to be reloaded and the API call made every time the view controller becomes visible whether or not you've made changes to it, you want the reloading to be done only when it's necessary.
You can try it in a few different ways:
class CreateProductVC: UITableViewController {
#IBAction func presentSecondVC() {
if let secondVC = storyboard?.instantiateViewController(identifier: "SecondVC") as? SecondViewController {
secondVC.delegate = self
present(secondVC, animated: true, completion: nil)
}
}
}
class SecondViewController: UIViewController {
weak var delegate: CreateProductVC?
#IBAction func dismissSecondVC() {
self.dismiss(animated: true) {
self.delegate?.tableView.reloadData()
}
}
}
or
class CreateProductVC: UITableViewController {
#IBAction func presentSecondVC() {
if let secondVC = storyboard?.instantiateViewController(identifier: "SecondVC") as? SecondViewController {
secondVC.isDismissed = { [weak self] in
self?.tableView.reloadData()
}
present(secondVC, animated: true, completion: nil)
}
}
}
class SecondViewController: UIViewController {
var isDismissed: (() -> Void)?
#IBAction func dismissSecondVC() {
self.dismiss(animated: true) {
self.isDismissed?()
}
}
}
or if you want more fine-grained control over what to do with the new data:
protocol ReloadVC {
func reload(_ value: String)
}
class CreateProductVC: UITableViewController, ReloadVC {
var dataSource: [String]! {
didSet {
tableView.reloadData()
}
}
#IBAction func presentSecondVC() {
if let secondVC = storyboard?.instantiateViewController(identifier: "SecondVC") as? SecondViewController {
secondVC.delegate = self
present(secondVC, animated: true, completion: nil)
}
}
func reload(_ value: String) {
dataSource.append(value)
}
}
class SecondViewController: UIViewController {
var delegate: ReloadVC?
#IBAction func dismissSecondVC() {
self.dismiss(animated: true) {
let someValue = "Some Value"
self.delegate?.reload(someValue)
}
}
}

interactivePopGestureRecognizer pop to root instead of 1 top controller

I use default implementation of UINavigationController with default gesture for popping left to right (interactivePopGestureRecognizer). How can I make interactivePopGestureRecognizer popping to root controller instead of only 1 top controller?
I found a way to just delete previous viewController from stack after pushing a new one.
navigationController.pushViewController(newViewController, animated: true, completion: {
self.navigationController.removePreviousViewController()
})
A here is an extension
extension UINavigationController {
func pushViewController(_ viewController: UIViewController, animated: Bool, completion: #escaping () -> Void) {
pushViewController(viewController, animated: animated)
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async { completion() }
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
func removePreviousViewController() {
if viewControllers.count > 2 {
viewControllers.removePrevious()
}
}
}
Some helpers
extension Array {
mutating func removePrevious() {
remove(at: count - 2)
}
}

View doesn't show with "setViewController" in a UIPageViewController in Swift

I would like to change the pages showed by my UIPageView programatically.
I created two ViewController that are intended to be displayed in the PageView, and I set the initial View with "setViewControllers" in my viewDidLoad. I works, the view is displayed and I can swipe on the screen to switch between the two views.
My problem being that when I try to call again "setViewControllers" to change the displayed view when I click a button, nothing happens.
I'm using delegates since the buttons are part of another ViewController, and used NSLog to make sure the functions were called, which is the case.
If anyone could help me understand why the "setViewControllers" method doesn't do anything, that would be great.
Here is my code for my UIPageViewController:
import UIKit
class FrontContentController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, sideMenuDelegate {
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return subViewControllers.count
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if currentIndex <= 0 {
return nil
}
return subViewControllers[currentIndex - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex:Int = subViewControllers.index(of: viewController) ?? 0
if currentIndex >= subViewControllers.count - 1 {
return nil
}
return subViewControllers[currentIndex + 1]
}
lazy var subViewControllers:[UIViewController] = {
return [
UIStoryboard(name: "frontPage", bundle: nil).instantiateViewController(withIdentifier: "FirstContent") as! FirstContentController,
UIStoryboard(name: "frontPage", bundle: nil).instantiateViewController(withIdentifier: "SecondContent") as! SecondContentController
]
}()
var sideMenuVC : SideMenuController!
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.dataSource = self
self.sideMenuVC = (self.storyboard?.instantiateViewController(withIdentifier: "SideMenu") as! SideMenuController)
self.setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
// Do any additional setup after loading the view.
}
func changeColor(_ color: UIColor) {
if color == .blue {
self.setViewControllers([subViewControllers[0]], direction: .forward, animated: false, completion: nil)
NSLog("Blue Delegate")
}
if color == .red {
self.setViewControllers([subViewControllers[1]], direction: .forward, animated: false, completion: nil)
NSLog("Red Delegate")
}
}
}
And in case it's relevant, the separate UIViewController with the buttons (a side menu) :
import UIKit
protocol sideMenuDelegate: AnyObject {
func changeColor(_ color : UIColor)
}
class SideMenuController: UIViewController {
weak var delegate : sideMenuDelegate?
var frontPageVC : FrontPageController!
var frontContentPC : FrontContentController!
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "frontPage", bundle: nil)
frontPageVC = (storyboard.instantiateViewController(withIdentifier: "FrontPage") as! FrontPageController)
frontContentPC = (storyboard.instantiateViewController(withIdentifier: "FrontContent") as! FrontContentController)
self.delegate = frontContentPC
self.view.backgroundColor = UIColor.black
}
#IBAction func pressBlueButton(_ sender: Any) {
delegate?.changeColor(UIColor .blue)
}
#IBAction func pressRedButton(_ sender: Any) {
delegate?.changeColor(UIColor .red)
}
}
Thanks

Admob Rewarded video - Root view controller issue

So I have two view controllers in my application:
StartViewController (Root view controller) and GameViewController
I am presenting my Rewarded video from GameViewController
Everything works perfectly, except for when the user presses "Skip now" on the rewarded video. It dismisses GameViewController and goes back to StartViewController which is my root view controller.
If the user watches the entire video, it works as intended.
The code for presenting rewarded view from GameViewController:
func playReward()
{
if rewardVideo!.isReady
{
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
while let presentedViewController = topController.presentedViewController
{
// Make top controller topmost view controller
topController = presentedViewController
}
rewardVideo!.present(fromRootViewController: topController)
}
}
}
I temporarily changed the root to GameViewController to see if this was the issue and doing so fixed it, so I know it is an issue related to the root view controller and the "Skip now" button on the rewarded video.
I had the same issue. I solved it by overriding the func dismiss(animated flag: Bool, completion: (() -> Void)? = nil method.
Here is what I did.
var didOpenRewardedVideo:Int = 0
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
if didOpenRewardedVideo == 1 {
didOpenRewardedVideo = 2
super.dismiss(animated: flag, completion: completion)
}
else if didOpenRewardedVideo == 2{
didOpenRewardedVideo = 0
}
else{
super.dismiss(animated: flag, completion: completion)
}
}
func showRewardedVideo()
{
didOpenRewardedVideo = 1
GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self)
}
Before showing the rewardedAd, do not forget to check if it's ready or not.
GADRewardBasedVideoAd.sharedInstance().isReady == true
When rewardedAd is presented didOpenRewardedVideo is set to 1. When user dismissing rewardedAd didOpenRewardedVideo is 1 and calling super.dismiss(animated: flag, completion: completion). Then didOpenRewardedVideo is set to 2. Now I know dismiss(animated flag: Bool, completion: (() -> Void)? = nil) will be called once more. This time I don't call the super method and set didOpenRewardedVideo to 0. I know if I dismiss my UIViewController will be dismissed.
#mialkan,
your solution does not work. I don't why no one talk about this issue. I am also facing such problem.
import GoogleMobileAds import sdk in your class or viewcontroller
GADRewardBasedVideoAdDelegate Add this in your class or viewcontroller
var RewardBasedVideo: GADRewardBasedVideoAd? **initialize AdController object **
override func viewDidLoad()
{
super.viewDidLoad()
RewardBasedVideo=GADRewardBasedVideoAd.sharedInstance()
RewardBasedVideo?.delegate = self
}
//MARK:- WATCH AD BUTTON CLICK
#IBAction func WatchAdBtn_Click(_ sender: UIButton)
{
if RewardBasedVideo?.isReady == true
{
RewardBasedVideo?.present(fromRootViewController: self)
} else
{
//Show alert here "Ads is not ready to load"
}
}
func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd)
{
print("Reward based video ad is closed.")
}
For those of you who is facing the the same issue:
You can create a new class for your rootViewController (TabBarController or NavigationController etc.) and implement there something like that:
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
dismissalCounter += 1
if (dismissalCounter < 2) {
super.dismiss(animated: flag, completion: completion)
}
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
dismissalCounter = 0
}
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
dismissalCounter = 0
super.present(viewControllerToPresent, animated: flag, completion: completion)
}
var dismissalCounter : Int = 0
Important! Use this functions inside TabBarController or NavigationController, otherwise it is not gonna work
UPD:
In my case unfortunatly it breaks all NavigationControllers inside a TabBarController (titles don't show and there are no buttons inside them), if I will figure fix actions, I'll let you know
UPD2:
Pretty obvious decision will be to change the initialViewController and view add from it, it'll not be dismissed
UPD3:
I solved this very and very strange:
class ViewController : UIViewController {
override func viewWillAppear(_ animated: Bool) {
if GADRewardBasedVideoAd.sharedInstance().isReady == false {
let request = GADRequest()
rewardBasedVideo!.load(request, withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
}
}
var rewardBasedVideo: GADRewardBasedVideoAd?
#IBAction func ad_button_click(_ sender: Any) {
if rewardBasedVideo!.isReady == true {
let bl = blur()
self.present(bl, animated: true, completion: {
self.rewardBasedVideo?.present(fromRootViewController: bl)
})
}
}
}
class blur : UIViewController {
override func viewDidLoad() {
checkForKeyWindow()
}
func checkForKeyWindow() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
if (UIApplication.topViewController() == self) {
print("dismissed and forgotten")
self.dismiss(animated: true, completion: nil)
} else {
print("not keywindow")
self.checkForKeyWindow()
}
})
}
#objc func close() {
self.dismiss(animated: true, completion: nil)
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController, top.view.window != nil {
return topViewController(base: top)
} else if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}

Tab Bar not appearing on applicationDidBecomeActive

Requirement - When user open Application from the background tabBar selected index should be 2
What i tried -
//For getting current visible controller -
public extension UIWindow {
public var visibleViewController: UIViewController? {
return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
}
public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
if let nc = vc as? UINavigationController {
return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
} else if let tc = vc as? UITabBarController {
return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
} else {
if let pvc = vc?.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(pvc)
} else {
return vc
}
}
}
}
let appdelegate = UIApplication.shared.delegate as! AppDelegate
//Selected 2 tabbar -
func applicationDidBecomeActive(_ application: UIApplication) {
if appdelegate.window?.visibleViewController != nil {
appdelegate.window?.visibleViewController?.hidesBottomBarWhenPushed = false
appdelegate.window?.visibleViewController?.navigationController?.popToRootViewController(animated: true)
appdelegate.window?.visibleViewController?.tabBarController?.selectedIndex = 2
appdelegate.window?.visibleViewController?.tabBarController?.tabBar.isHidden = false
appdelegate.window?.bringSubview(toFront: (appdelegate.window?.visibleViewController?.tabBarController?.view)!)
}
}
The code is working fine but problem is Tabbbar get hidden. Why?
This will work if each tab has a navigationController
if let tabController = self.window!.rootViewController as? UITabBarController {
if let navController = tabBarController.selectedViewController as? UINavigationController{
navController.popToRootViewController(animated: true)
tabBarController.selectedIndex = 2
}
}
You need to subclass UITabBarViewController
override viewWillAppear method.
Subscrib UIApplicationWillEnterForeground notification.
Set selectedIndex on notification received.
class HomeViewController: UITabBarController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector:#selector(applicationWillEnterForeground(notification:)), name: .UIApplicationWillEnterForeground, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.removeObserver(self, name: .UIApplicationWillEnterForeground, object: nil)
}
#objc private func applicationWillEnterForeground(notification: Notification) {
selectedIndex = 2
}}

Resources