我想使用Singleton来展示广告,但效果不佳。 当我不使用Singleton并且只使用ViewController时,它运行良好。(可以通过“vampLoadStart”和“vampDidReceive”)
我该如何解决?
模式1:当我使用Singleton时(无法加载并显示广告)
VAMPAdReward.swift
import Foundation
import UIKit
import VAMP
class VAMPAdReward: NSObject,VAMPDelegate{
static let sharedInstance = VAMPAdReward()
var adReward:VAMP!
override init() {
super.init()
}
func loadAdReward(parentViewController: UIViewController) {
adReward = VAMP()
adReward.setPlacementId("26812") //test ID
adReward.delegate = self
adReward.setRootViewController(self)
}
func showAdReward(){
if adReward.isReady() {
print("show ad")
adReward.show()
}else{
print("couldn't show ad")
}
}
func vampLoadStart(_ placementId: String!, adnwName: String!) {
print("start loading")
}
func vampDidReceive(_ placementId: String!, adnwName: String!) {
print("finished loading")
}
}
的ViewController
import UIKit
class ViewController: UIViewController {
var adReward: VAMPAdReward!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
VAMPAdReward.sharedInstance.loadAdReward(parentViewController: self)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
//when touch screen, show Ad
VAMPAdReward.sharedInstance.showAdReward()
}
}
模式2:当我不使用Singleton时(可以加载和显示广告)
import UIKit
import VAMP
class ViewController: UIViewController, VAMPDelegate {
var ad: VAMP!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
//load ad
ad = VAMP()
ad.setPlacementId("59755") //test ID
ad.delegate = self
ad.setRootViewController(self)
ad.load()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
ad.show()
}
func vampLoadStart(_ placementId: String!, adnwName: String!) {
print("start loading") //through
}
func vampDidReceive(_ placementId: String!, adnwName: String!) {
print("finished loading") //through
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:2)
按照以下步骤完成单件类
// MARK: - Singleton
final class Singleton {
// Can't init is singleton
private init() { }
// MARK: Shared Instance
static let shared = Singleton()
// MARK: Local Variable
var emptyStringArray : [String] = []
}
答案 1 :(得分:1)
单身的正确方法
func loadAdReward(parentViewController: UIViewController) {
adReward = VAMP()
adReward.setPlacementId("26812") //test ID
adReward.delegate = self
adReward.setRootViewController(parentViewController)
adReward.load()
}