gpt4 book ai didi

ios - 移除广告 - 应用内购买

转载 作者:行者123 更新时间:2023-11-29 00:56:48 25 4
gpt4 key购买 nike

在我的游戏中,我希望通过应用内购买来移除广告。我使用 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

类实用程序{

// 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 步:购买产品()

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
}

最佳答案

首先,我不精通 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];
}

将这些方法复制并粘贴到某个文件中。如果您使用实用程序/帮助程序文件,请将其放在那里,因为它们可以是静态方法(“+”符号),因此它们可以存在于任何地方。将这些方法中的 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 类的 viewDidLoad 方法的修改版本,它包含了 not 的逻辑包括在将来加载该 View 时添加的内容:

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

关于ios - 移除广告 - 应用内购买,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com