Тема 1 проблемы Swift Admob: EXC_BAD_INSTRUCTION

Я работаю над следующей проблемой уже пару дней, и я немного расстроен этим. Итак, у меня есть файл проекта https://github.com/PCmex/lift-side-memu-in-swift-3, и я успешно запустил Cocoapod с его помощью. Я следовал всему руководству по admob и выполнил все необходимые шаги. Когда я пытаюсь протестировать приложение, сборка в порядке, но после запуска приложение вылетает и дает мне следующую информацию:

Снимок экрана с сообщением об ошибке: Thread 1: EXC_BAD_INSTRUCTION

В журнале содержится следующая информация: Версия Google Mobile Ads SDK: (GADRequest.sdkVersion()) неустранимая ошибка: неожиданно найдено nil при распаковке необязательного значения (lldb)

Вот делегат приложения.swift

import UIKit
import GoogleMobileAds
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    //Use Firebase library to configure APIs
    FirebaseApp.configure()
    GADMobileAds.configure(withApplicationID: "ca-app-pub-***")
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

А это ViewController.swift

import UIKit
import GoogleMobileAds
import Firebase

class ViewController: UIViewController {

@IBOutlet weak var btnMenuButton: UIBarButtonItem!
@IBOutlet weak var bannerView: GADBannerView!
override func viewDidLoad() {
    super.viewDidLoad()

    // Aanroepen print functie voor de Google AdMob banner
    print("Google Mobile Ads SDK version:(GADRequest.sdkVersion())")
    bannerView.adUnitID = "ca-app-pub-***"
    bannerView.rootViewController = self
    bannerView.load(GADRequest())

    // Do any additional setup after loading the view, typically from a nib.
    if revealViewController() != nil {
        //            revealViewController().rearViewRevealWidth = 62
        btnMenuButton.target = revealViewController()
        btnMenuButton.action = #selector(SWRevealViewController.revealToggle(_:))

//            revealViewController().rightViewRevealWidth = 150
//            extraButton.target = revealViewController()
//            extraButton.action = "rightRevealToggle:"




    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Я почти уверен, что правильно устанавливал Coco-Pod/AdMob и все предпосылки. Когда я делаю все шаги в новом проекте, все работает нормально. Но я пытаюсь понять, почему это не работает в моем текущем проекте. Надеюсь, кто-то может указать мне в правильном направлении, спасибо заранее!


person DeDe Schurk    schedule 17.07.2017    source источник


Ответы (1)


Переменная bannerView является неявно развернутой опцией. Это означает, что это является необязательным типом переменной. Помните, что необязательные параметры развертывания сбой, если его значение равно nil, поэтому обычно вы должны выполнить некоторую необязательную цепочку, например if let, для проверки перед развертыванием, чтобы предотвратить сбой. В вашем случае bannerView равно nil, поэтому ваше приложение разбилось. Неявно развернутый необязательный элемент объявляется путем размещения ! после его типа (в вашем случае GADBannerView!).

Я предлагаю вам перейти в раскадровку (или XIB) вашего контроллера, выбрать свой GADBannerView и перейти к инспектору соединений.

инспектор соединений

И проверьте, есть ли что-нибудь в разделе "Referenceing Outlets" (кроме "New Referencing Outlet"). Если есть, разорвите соединение, нажав кнопку X.

Разорвать соединение

Затем удалите линию @IBOutlet weak var bannerView в контроллере и снова подключите GADBannerView к ViewController. Если в разделе ничего нет, просто удалите @IBOutlet weak var bannerView и переподключите GADBannerView к ViewController

person paper1111    schedule 17.07.2017