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

Frustrating memory leak when loading an interstitial ad in Swift

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

我已经尝试在 Instruments 中对此进行分析,分配的内存都是系统库,没有任何东西指出错误。我已经阅读了其他 Stack Overflow 答案,例如 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.

我只想说,这其实已经被我解决了。我按照评论中的上述内容之一做了。我将托管插页式广告的视图控制器上的代码移至应用程序委托。然后,只要我在项目中需要它,我就可以引用插页式广告对象。这使内存回到访问托管广告的控制器时分配的内存。对于那些想看一个非常简单的应用程序委托示例的人:

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

我也遇到了这个问题,结果我只需要更新一个 pod。

在版本 7.53.0 中,更新包括 'Fixed the GADBlockSignalSource memory leak that occurred when loading ads' 这可能与我们遇到的间隙内存泄漏问题有关。

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