admobgestureshake

Google AdMob interfering with Shake Gesture in SwiftUI


I have an app built in SwiftUI that uses a shake gesture, which has worked perfectly throughout development. Today I added a banner ad using AdMob successfully. However, doing so appears to prevent the Shake Gesture from working. The individually working AdMob and Shake Gesture code is shown below.

The AdMob Banner Ad is called with the following:

final private class BannerVC: UIViewControllerRepresentable  {

    let bannerID = “my-BannerAd-Unit-ID-here“

    func makeUIViewController(context: Context) -> UIViewController {
        let view = GADBannerView(adSize: kGADAdSizeBanner)

        let viewController = UIViewController()
        view.adUnitID = bannerID
        view.rootViewController = viewController
        viewController.view.addSubview(view)
        viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
        view.load(GADRequest())

        return viewController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}



struct BannerAdView: View {
    var body: some View {
//        Text("Hello, World!")

        HStack{
            Spacer()
            BannerVC().frame(width: 320, height: 50, alignment: .center)
            Spacer()
        }

    }
}

In the BannerAdView, the Shake Gesture works fine if I comment out the BannerVC call and replace it with the "Hello World" text. When I comment out "Hello World" and replace with the BannerVC call (as shown above), the Shake Gesture no longer works. As such, the interference seems to be coming from the BannerVC class code.

Any idea why? Following is the working code for the Shake Gesture:

struct ShakableViewRepresentable: UIViewControllerRepresentable {

    class Coordinator: NSObject {
        var parent: ShakableViewRepresentable
        init(_ parent: ShakableViewRepresentable) {
            self.parent = parent
        }
    }

    func makeCoordinator() -> ShakableViewRepresentable.Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> ShakableViewController {
        ShakableViewController()
    }

    func updateUIViewController(_ uiViewController: ShakableViewController, context: Context) {}
}

class ShakableViewController: UIViewController {

    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        guard motion == .motionShake else { return }
        shuffleItems(newGame: false)
    }
}

Solution

  • So, the problem had nothing to do with AdMob. Instead, the bug was due to the fact that I had two UIViewControllers in my stack (one for the shaker and one for AdMob). Once I fixed that, it worked perfectly.