在Swift中加载插页式广告时令人沮丧的内存泄漏

时间:2019-04-26 22:20:38

标签: ios swift admob interstitial

关于通过AdMob加载插页式广告,我正在处理令人震惊的内存泄漏。在Xcode&Instruments中观察内存时,每次我访问托管广告的视图控制器时,内存就会跳跃10 MB。同样,当关闭手机上的应用程序并重新打开它时,也会导致内存也跳30-40 mb,这简直太荒谬了。

我曾尝试在Instruments中对其进行性能分析,并且分配的内存都是系统库,没有任何东西指出错误所在。我已经阅读了其他堆栈溢出答案,例如ADMOB Memory Leaking? 但到目前为止,没有答案对我有帮助。也许有人可以告诉我我的代码有什么问题?我已经按照AdMob提供的确切文档进行了https://developers.google.com/admob/ios/interstitial的操作,除了这种疯狂的内存泄漏之外,其他所有方法都工作正常。这是导致以下泄漏的确切代码。


class ViewController: UIViewController, GADInterstitialDelegate {

var interstitial: GADInterstitial!

override func viewDidLoad() {
  interstitial = createAndLoadInterstitial()
  interstitial.delegate = self
}

func update() {
        if interstitial.isReady {
            interstitial.present(fromRootViewController: self)
        }
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        let interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        interstitial = createAndLoadInterstitial()
    }

// I am calling update() inside a button when pressed in this VC.

2 个答案:

答案 0 :(得分:0)

我只想说这实际上已经由我解决了。我按照评论中的上述说明之一做了。我将托管插页式广告的视图控制器上的代码移到了应用程序委托中。然后,只要在项目中需要时,我便只是引用了插页式广告对象。这样,在访问托管广告的控制器时,内存便恢复为分配的所有内存。对于那些希望在应用程序委托中看到一个非常简单的示例的人:

import UIKit
import GoogleMobileAds

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GADInterstitialDelegate {

    var myInterstitial: GADInterstitial!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        myInterstitial = createAndLoadInterstitial()
        return true
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        let interstitial = GADInterstitial(adUnitID: "yourAdID")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        return interstitial
    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        myInterstitial = createAndLoadInterstitial()
    }

答案 1 :(得分:0)

我也遇到了这个问题,原来我只需要更新Pod。

在7.53.0版中,更新内容包括“修复了加载广告时发生的GADBlockSignalSource内存泄漏”,这可能与我们遇到的插页式内存泄漏问题有关。

发行说明: https://developers.google.com/admob/ios/rel-notes