2016-05-31 16 views
0

私のゲームでは、広告を削除するためのアプリ内購入があります。私はAdmobを使用しています。私のコードは広告に適しています。私が持っている問題は、広告のコードがGameViewController.swiftにあることです。しかし、私のアプリ内購入は私のPurchaseScene.swiftにあります。広告を削除する - アプリ内購入

私はPurchaseScene.swiftで削除機能を実行する方法を見つけませんでした。だから私は私のGameViewController.swiftにあるコード:

class GameViewController: UIViewController, GADBannerViewDelegate, GADInterstitialDelegate { 

    @IBOutlet weak var banner: GADBannerView! 

    var interstital: GADInterstitial! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ShowAd(_:)), name: "ShowInterAdKey", object: nil) 

     if let scene = GameScene(fileNamed:"GameScene") { 
      // Configure the view. 
      let skView = self.view as! SKView 
      skView.showsFPS = false 
      skView.showsNodeCount = false 

      /* Sprite Kit applies additional optimizations to improve rendering performance */ 
      skView.ignoresSiblingOrder = true 

      /* Set the scale mode to scale to fit the window */ 
      scene.scaleMode = .AspectFill 
      scene.size = self.view.bounds.size 

      skView.presentScene(scene) 
     } 

     self.banner.adUnitID = "myUnitID" 
     self.banner.rootViewController = self 

     var request: GADRequest = GADRequest() 

     self.banner.loadRequest(request) 

     request.testDevices = [kGADSimulatorID] 

     interstital = GADInterstitial(adUnitID: "myUnitID") 

     let req = GADRequest() 
     interstital.loadRequest(req) 
    } 

    func adViewDidReceiveAd(bannerView: GADBannerView!) { 
     banner.hidden = false 
    } 

    func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) { 
     banner.hidden = true 
    } 

    override func shouldAutorotate() -> Bool { 
     return true 
    } 

    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { 
     if UIDevice.currentDevice().userInterfaceIdiom == .Phone { 
      return .AllButUpsideDown 
     } else { 
      return .All 
     } 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Release any cached data, images, etc that aren't in use. 
    } 

    override func prefersStatusBarHidden() -> Bool { 
     return true 
    } 

    func ShowAd(sender: AnyObject) { 
     if (interstital.isReady) { 
      interstital.presentFromRootViewController(self) 
      interstital = CreateAd() 
     } 

    } 

    func CreateAd() -> GADInterstitial { 
     let interstital = GADInterstitial(adUnitID: "myUnitID") 
     interstital.loadRequest(GADRequest()) 
     return interstital 
    } 
} 

そして今私はこのコードをUtilities.swiftに持っています。

let file = "IAP_Ads" 



func removeADS() { 

    Utility.writeValueToFile("YES", fileName: file); 




if let value = Utility.readValueFromFile(file) { 
    print("file exists... value = %@" , Utility.readValueFromFile(file)) 

    let adsRemoved = (value == "YES" ? true : false) 

    if adsRemoved { 
     // Code to remove ads, but i don't know what code 
     print("ads removed") 


    } 
} 
} 
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    for touch: AnyObject in touches{ 
     let location = touch.locationInNode(self) 
     var node = self.nodeAtPoint(location) 
if removeadsBTN.containsPoint(location){ 
      for product in list { 
       let prodID = product.productIdentifier 
       if(prodID == "myProductID") { 
        p = product 
        buyProduct() 
        break; 
       } 
      } 
     } 

    } 


} 

ステップ3:

import Foundation 

クラスユーティリティ{

// Gets a path to your app's local directory where it has permissions to write 
static func getFilePathForFile(fileName:String) -> String { 
    let libraryPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] 

    return libraryPath.stringByAppendingString("/").stringByAppendingString(fileName as String) 
} 

static func writeValueToFile(value:String, fileName:String) { 

    do { 
     try value.writeToFile(Utility.getFilePathForFile(fileName), atomically: true, encoding: NSUTF8StringEncoding) 
    } catch { 
     print("\(error)") 
    } 
} 

static func readValueFromFile(fileName:String) -> String? { 

    let file = Utility.getFilePathForFile(fileName); 

    if let value = try? String(contentsOfFile: file) { 
     return value; 
    } 

    return nil; 
} 

}

、通話機能は、このようなPurchaseScene.swiftであるbuyProduct()

func buyProduct() { 
    print("buy " + p.productIdentifier) 
    let pay = SKPayment(product: p) 
    SKPaymentQueue.defaultQueue().addTransactionObserver(self) 
    SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment) 
    Utility.writeValueToFile("YES", fileName: "IAP_Ads") //new code 
} 
+0

購入画面はGameViewControllerとは別のものとしますか?もしそうなら、画面を変更しなければならない(例えば、ナビゲーションコントローラ経由でpush/popのように)、 'viewWillAppear'関数が呼び出されたとき、GameViewController内の" purchase "の状態を調べるだけです。オーバーレイ経由でGameViewControllerのライフサイクルメソッドが呼び出されない場合は、オブザーバー/通知モデルを使用する必要があります。 – thephatp

+0

@thephatpはい別途購入画面があります。 GameViewControllerの「購入」の状態を確認するにはどうすればよいですか?コード例がありますか?ありがとうございます。 – Claudio13

+0

追跡状態は悪くありませんが、これは購入であるため、ユーザーがデバイスを変更した場合、購入時点を復元できるようにしたいと考えています。後でそれを覚えておいてください。今のところ、「状態を見つける」に入るだけで、コードを手に入れましょう。コアデータを使用していますか? (これは、あまりにも多くの仕事を与えることなく、適切なコードを与えるのに役立ちます。) – thephatp

答えて

1

まず、Swiftに堪能ではありませんが、Objective-Cがわからない場合は、これを変換することができます。ちょっと時間がかかります。

これは理想的な解決策ではないかもしれませんが、すぐに起動して実行する必要があります。何が起きているのかを理解すれば、必要に応じてコードを変更できます。たとえば、複数の値を1つのファイルに格納することができます。あなたがこれを行う場合は、JSON形式を使用することができ、またはあなただけのようなフォーマットを行いますし、どこかのファイルに

// Gets a path to your app's local directory where it has permissions to write 
+ (NSString *)getFilePathForFile:(NSString *)fileName 
{ 
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    return [libraryPath stringByAppendingPathComponent:fileName]; 
} 

// Writes a value to a file. Cast your value to a string before passing it in. 
+ (void)writeValue:(NSString *)value toFile:(NSString *)file 
{ 
    [value writeToFile:[self getFilePathForFile:file] atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 
} 

// Reads a value from a file. Once you have this value, cast it back to the type you need. 
+ (NSString *)readValueFromFile:(NSString *)file 
{ 
    NSString *filePath = [self getFilePathForFile:file]; 

    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
     return nil; 

    return [NSString stringWithContentsOfFile:filePath 
            encoding:NSUTF8StringEncoding 
             error:NULL]; 
} 

コピーして、これらのメソッドを過ぎなど、改行が値を分離しましょう。ユーティリティ/ヘルパーファイルを使用する場合は、静的メソッド( '+'記号)にすることができるので、どこにでも置くことができます。これらの方法ではselfを、入れたクラスに置き換えてください。

次に、以下のように呼び出します。

// User purchased to remove adds, so let's save that now. (IAP stands for In-App Purchase 
[self writeValue:@"YES" toFile:@"IAP_RemoveAds"]; 

を読むには:書き込みに

// Loading my new view, so need to check to see if the removal of ads was purchased... 
NSString * sPurchased = [self readValueFromFile:@"IAP_RemoveAds"]; 
BOOL removeAds = [sPurchased boolValue]; 

は、この情報がお役に立てば幸いです。

スウィフトコード:ファイルでこれを入れて

は、たとえばUtilities.swiftそれを呼び出す:

import Foundation 

class Utility { 

    // Gets a path to your app's local directory where it has permissions to write 
    static func getFilePathForFile(fileName:String) -> String { 
     let libraryPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] 

     return libraryPath.stringByAppendingString("/").stringByAppendingString(fileName as String) 
    } 

    static func writeValueToFile(value:String, fileName:String) { 

     do { 
      try value.writeToFile(Utility.getFilePathForFile(fileName), atomically: true, encoding: NSUTF8StringEncoding) 
     } catch { 
      print("\(error)") 
     } 
    } 

    static func readValueFromFile(fileName:String) -> String? { 

     let file = Utility.getFilePathForFile(fileName); 

     if let value = try? String(contentsOfFile: file) { 
      return value; 
     } 

     return nil; 
    } 
} 

はこのようにそれを呼び出します。

let file = "IAP_Ads" 

// Writing to the file 
Utility.writeValueToFile("YES", fileName: file); 


// Reading from the file 
if let value = Utility.readValueFromFile(file) { 
    print("file exists... value = %@" , Utility.readValueFromFile(file)) 

    let adsRemoved = (value == "YES" ? true : false) 

    if adsRemoved { 
     print("ads removed") 

     // Remove the ads here 
    } 
} 

そして、私は維持することはできませんので、私はあなたのGameViewControllerクラス 'viewDidLoadメソッドの修正バージョンをwhの下に置きますそのビューが将来読み込まれるたびに追加を含まないロジックを組み込んでいます:

override func viewDidLoad() { 
    super.viewDidLoad() 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ShowAd(_:)), name: "ShowInterAdKey", object: nil) 

    if let scene = GameScene(fileNamed:"GameScene") { 
     // Configure the view. 
     let skView = self.view as! SKView 
     skView.showsFPS = false 
     skView.showsNodeCount = false 

     /* Sprite Kit applies additional optimizations to improve rendering performance */ 
     skView.ignoresSiblingOrder = true 

     /* Set the scale mode to scale to fit the window */ 
     scene.scaleMode = .AspectFill 
     scene.size = self.view.bounds.size 

     skView.presentScene(scene) 
    } 

    if let value = Utility.readValueFromFile(file) { 

     let adsRemoved = (value == "YES" ? true : false) 

     if !adsRemoved { 
      // Ads have not been purchased yet, so show the ads 

      self.banner.adUnitID = "myUnitID" 
      self.banner.rootViewController = self 

      var request: GADRequest = GADRequest() 

      self.banner.loadRequest(request) 

      request.testDevices = [kGADSimulatorID] 

      interstital = GADInterstitial(adUnitID: "myUnitID") 

      let req = GADRequest() 
      interstital.loadRequest(req) 
     } 
    } 
} 
+0

残念ながらObjective-Cを使ったことがないので、これを翻訳することはできません。 「どこかのファイルにメソッドを貼り付ける」とはどういう意味ですか?このコードをGameViewControllerに貼り付けるべきではありませんか? – Claudio13

+0

@ Claudio13更新答え。これがあなたのために働くのか、それとも他の質問があれば教えてください。 'Utility.writeValueToFile(...を入れてください) 'あなたの' PurchaseScene.swift'ファイルを呼び出して購入を確認します。 GameViewControllerのファイルから読み込み用のロジックをviewDidLoadに入れて広告を削除します。 – thephatp

+0

申し訳ありませんが、私は少し摂取に遅いが、私は初心者です。コードは現時点では機能しませんが、私はそれを正しい場所に置かないでください、または何かを間違えたと思います。私は新しいファイルUtilities.swiftを作り、コードをそこに置いた。しかし、2番目のコードは機能しません。助けとあなたの持久力をありがとう! – Claudio13

関連する問題