Swift / Xcode 9 - 在App Purchase中 - 在展开Optional值时意外发现nil

时间:2017-09-28 11:17:42

标签: ios swift in-app-purchase itunesconnect

我在从我的应用中删除广告时遇到了一些困难。

问题是当我点击删除广告按钮时,应用程序崩溃并显示消息fatal error: unexpectedly found nil while unwrapping an Optional value

我在网上看过,但是,它们似乎已经过时了。

我查看了我的控制台,我可能发现了错误product = (SKProduct)nil

有趣的是,我之前曾经实施过这种方法并且遇到了同样的问题,而且它已经成功了。所以我只是重新使用了代码并更改了productID

我想也许需要时间来实际注册应用内购买的ID。但是,我已经醒来了同样的问题。有人可以帮助我,告诉我这个问题是什么?

点按“删除广告”按钮后,我的游戏崩溃了。我的删除按钮的操作/方法是removeAds_TouchUpInside

import UIKit
import SpriteKit
import GameplayKit
import GoogleMobileAds
import StoreKit

class GameViewController: UIViewController, GADInterstitialDelegate, SKPaymentTransactionObserver, SKProductsRequestDelegate {
    var fullScreenAds : GADInterstitial!
    @IBOutlet weak var removeAdsButton: UIButton!

    var product: SKProduct?
    var productID = "com.USER.GAME.removeAds"

    override func viewDidLoad() {
       super.viewDidLoad()

        let save = UserDefaults.standard
        if save.value(forKey: "Purchase") == nil  {
            let request = GADRequest()
            request.testDevices = [kGADSimulatorID]
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadAds"), object: nil)

        } else {
        }
              if let view = self.view as! SKView? {
            if let scene = SKScene(fileNamed: "GameMenuScene") {
                scene.scaleMode = .aspectFill
                view.presentScene(scene)
                }
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
        }
    }

    override func viewDidAppear(_ animated: Bool) {
      super.viewDidAppear(animated)
    }

    @IBAction func removeAds_TouchUpInside(_ sender: Any) {
        let payment = SKPayment(product: product!)
        SKPaymentQueue.default().add(payment)
    }

    override func viewWillLayoutSubviews() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.loadAds), name: NSNotification.Name(rawValue: "loadAds"), object: nil)
    }
    func loadAds() {
        self.fullScreenAds = createAndLoadInterstitials()

    }
    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    func createAndLoadInterstitials() -> GADInterstitial? {
        fullScreenAds = GADInterstitial(adUnitID: "ca-app-pub-7212561254132738/9424537183")
        guard let fullScreenAds = fullScreenAds else {
            return nil
        }

        let request = GADRequest()
        request.testDevices = [kGADSimulatorID]
        fullScreenAds.load(request)
        fullScreenAds.delegate = self

        return fullScreenAds
    }

    func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print("Ad received")
        ad.present(fromRootViewController: self)
    }

    func interstitialDidFail(toPresentScreen ad: GADInterstitial) {
        print("No ad can be loaded")

    }

    func getPurchaseInfo() {
        if SKPaymentQueue.canMakePayments() {
            let request = SKProductsRequest(productIdentifiers: NSSet(objects: self.productID) as! Set<String>)
            request.delegate = self
            request.start()
        } else {
            print("Enable in app purchase!")
            return
        }
    }

    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        var products = response.products

        if (products.count == 0) {
            print("Error")
            return
        } else {
            product = products[0]
            removeAdsButton.isEnabled = true
            print("Succes!")
        }

        let invalids = response.invalidProductIdentifiers

        for product in invalids {
            print("Product not found \(product)")
        }
    }
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch transaction.transactionState {
            case SKPaymentTransactionState.purchased:
                SKPaymentQueue.default().finishTransaction(transaction)
                print("SuccessPayementQeue!")
                removeAdsButton.isEnabled = false
                let save = UserDefaults.standard
                save.set(true, forKey: "Purchase")
                save.synchronize()

            case SKPaymentTransactionState.failed:
                SKPaymentQueue.default().finishTransaction(transaction)
                print("Failed transaction state")
            default:
                break
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

由于产品nil,您面临问题,因此您可以编写如下代码来解决问题。

@IBAction func removeAds_TouchUpInside(_ sender: Any) {
        if let myP = product {
           let payment = SKPayment(product: myP)
           SKPaymentQueue.default().add(payment)
        }
        else {
            print("Product is not found.")
        }
}