删除广告 - 在应用内购买

时间:2016-05-31 17:05:32

标签: ios swift sprite-kit in-app-purchase

在我的游戏中,我想让In App Purchase删除广告。我使用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中有这段代码。

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;
}

}

调用函数在PurchaseScene.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步: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
}

1 个答案:

答案 0 :(得分:1)

首先,我不熟悉Swift,但如果你不了解Objective-C,我可以尝试为你转换它,它会让我多花一点时间

现在,这可能不是理想的解决方案,但它可以帮助您快速启动并运行。一旦了解了正在发生的事情,您就可以修改代码以满足您的需求。例如,您可以选择在单个文件中存储多个值。如果你这样做,你可以使用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];
}

将这些方法复制并传递到某个文件中。如果您使用实用程序/辅助文件,请将其放在那里,因为这些可以是静态方法(&#39; +&#39;符号),因此它们可以存在于任何地方。将这些方法中的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];

希望这会有所帮助。

Swift代码:

将它放在一个文件中,比如称之为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课程的修改版本&#39;下面的viewDidLoad方法包含了在将来加载视图时不包括添加的逻辑:

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)
        }
    }
}
相关问题