因此,我尝试在应用程序中设置一个简单的iAd标语,但在输出中收到以下两个警告:
WARNING: More than 10 instances of ADBannerView or ADInterstitialView currently exist. This is a misuse of the iAd API, and ad performance will suffer as a result. This message is printed only once.
和
<Error>: CGAffineTransformInvert: singular matrix.
这就是我用来实现我的ADBannerView:
ADBannerView
var adBannerView = ADBannerView() func loadAds() { adBannerView = ADBannerView(frame: CGRect.zeroRect) adBannerView.center = CGPoint(x: adBannerView.center.x, y: view.bounds.size.height - adBannerView.frame.size.height / 2) adBannerView.delegate = self adBannerView.hidden = true view.addSubview(adBannerView) } //BannerView did load ad func bannerViewDidLoadAd(banner: ADBannerView!) { adBannerView.hidden = false } //BannerView failed to load func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { adBannerView.hidden = true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. loadAds() //(rest of the code is from here onwards)
我尝试添加此代码以停止第一个错误:(无效)
//BannerView will disappear override func viewWillDisappear(animated: Bool) { adBannerView.removeFromSuperview() adBannerView.delegate = nil }
问题在于,每次加载视图时,您都会创建一个新的实例ADBannerView。我们需要做的是ADBannerView在我们的视图中创建一次AppDelegate.swift,然后ADBannerView在我们希望使用iAd横幅的任何视图上展示该视图。这也称为“ 共享iAd标语”。在这个例子中,我创建了一个ADBannerView在我AppDelegate.swift,然后把它添加到我ViewController.swift的观点。
AppDelegate.swift
ViewController.swift
import UIKit import iAd // Import iAd @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, ADBannerViewDelegate { // Include the delegate for our banner var window: UIWindow? var adBannerView = ADBannerView() // Create our one ADBannerView func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Set delegate and hide banner initially adBannerView.delegate = self adBannerView.hidden = true return true } func bannerViewDidLoadAd(banner: ADBannerView!) { print("bannerViewDidLoadAd") adBannerView.hidden = false } func bannerViewActionDidFinish(banner: ADBannerView!) { print("bannerViewActionDidFinish") } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { print("didFailToReceiveAdWithError: \(error)") adBannerView.hidden = true }
import UIKit class ViewController: UIViewController { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // Create reference to our app delegate override func viewWillAppear(animated: Bool) { // Position appDelegate.adBannerView.center = CGPoint(x: view.frame.midX, y: view.frame.height - appDelegate.adBannerView.frame.height / 2) // Add to view view.addSubview(appDelegate.adBannerView) }
不要忘记从viewWillDisappear(animated: Bool)以前添加的函数中删除代码。如果您单击横幅,然后将其关闭,则将调用此函数,并且从视图中删除横幅并将横幅委托设置为nil太早会导致问题。
viewWillDisappear(animated: Bool)