Reputation: 1243
I'm getting a fatal crash when trying to place an admob interstitial ad in my Swift, SpriteKit, iOS9 game.
I believe I've got the Admob SDK and dependencies set-up properly, via CocoaPods, following the streamlined instructions here: https://developers.google.com/admob/ios/quick-start
My Podfile:
platform :ios, '7.0'
use_frameworks!
source 'https://github.com/CocoaPods/Specs.git'
pod 'Google-Mobile-Ads-SDK', '~> 7.0'
target 'My Project's Name' do
end
Then I follow this guide: https://developers.google.com/admob/ios/interstitial
It's a game, so I put the code in GameViewController.swift (rather than ViewController.swift.) The relevant bits:
import GoogleMobileAds
class GameViewController: UIViewController, GADInterstitialDelegate {
var interstitial: GADInterstitial!
override func viewDidLoad() {
super.viewDidLoad()
print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion())
self.interstitial = createAndLoadInterstitial()
// unrelated code
}
}
func createAndLoadInterstitial() -> GADInterstitial {
var interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
interstitial.delegate = self
interstitial.loadRequest(GADRequest())
return interstitial
}
func interstitialDidDismissScreen(ad: GADInterstitial!) {
self.interstitial = createAndLoadInterstitial()
}
func gameOver() {
if self.interstitial.isReady {
self.interstitial.presentFromRootViewController(self)
}
}
I get the proper output in console: Google Mobile Ads SDK version: afma-sdk-i-v7.7.0
But I get this error on the gameOver() function:
fatal error: unexpectedly found nil while unwrapping an Optional value
It appears to be on the if self.interstitial.isReady
line.
I did make the App Transport Security (ATS) allowance detailed here: https://developers.google.com/admob/ios/ios9
XML looks like:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I also tried changing out the ad unit ID from the above (the test code Google has in instructions) with my actual ad ID, but no dice -- same error.
Any suggestions would be appreciated.
Cheers, Kevin
Upvotes: 0
Views: 422
Reputation: 10674
Are you checking that the ad has preloaded correctly and therefore is not nil?
You can also add a check just before the ...isReady line
guard self.interstitial != nil else { return }
to make sure its not nil.
If you are still stuck I have an ads helper on gitHub you an check out, it includes adMob as well
https://github.com/crashoverride777/Swift2-iAds-AdMob-CustomAds-Helper
Upvotes: 2