移除广告 - 应用内购买
Remove Ads - 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实用程序{
// 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];
}
将这些方法复制并粘贴到某个文件中。如果你使用 utility/helper 文件,把它放在那里,因为这些可以是静态方法('+' 符号),所以它们可以存在于任何地方。将这些方法中的 self
替换为您放置它们的 Class。
接下来,像下面这样调用它。
要写:
// 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
class' viewDidLoad
方法的修改版本,其中包含 not 的逻辑包括将来加载该视图时的添加:
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)
}
}
}
在我的游戏中,我想通过应用内购买来移除广告。我使用 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实用程序{
// 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];
}
将这些方法复制并粘贴到某个文件中。如果你使用 utility/helper 文件,把它放在那里,因为这些可以是静态方法('+' 符号),所以它们可以存在于任何地方。将这些方法中的 self
替换为您放置它们的 Class。
接下来,像下面这样调用它。
要写:
// 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
class' viewDidLoad
方法的修改版本,其中包含 not 的逻辑包括将来加载该视图时的添加:
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)
}
}
}