2017-09-28 21 views
-1

내 앱에서 광고를 삭제하는 데 어려움이 있습니다.Swift/Xcode 9 - In App Purchases - 옵션 값을 래핑하지 않고 예기치 않게 발견됨

문제는 내가 광고 제거 버튼을 클릭하면 응용 프로그램이 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 
      } 
     } 
    } 
} 
+0

가능한 중복 (https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly -found-nil-while-unwrap-an-optional-valu) – Shades

+0

@Shades 나는 치명적인 오류가 무엇인지 알고있다. 먼저 'guard'또는'if let '을 사용하여 값을 언 랩핑해야하지만, 인앱 구매이다. 그래서 저는 큰 우둔한 사람입니다. 희망이 모든 것을 명확히합니다. :) – SwiftLearner

답변

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.") 
     } 
} 
+0

인쇄물이 '제품을 찾을 수 없습니다.'라고 표시되는 것 같습니다. – SwiftLearner

+0

예, 제품을 찾을 수없는 이유를 살펴보아야합니까? check product_id가 맞는지 여부를 나타냅니다. – Govaadiyo

+0

내 제품 ID가 정확합니다. 이전에이 문제가 발생하여 갑자기 작동하기 시작했습니다. – SwiftLearner