简体   繁体   English

如何检测 iOS App Extension 中的内存警告

[英]How to detect memory warnings in iOS App Extension

I'm writing an iOS extension that extends NEPacketTunnelProvider in the NetworkExtension framework released in iOS 9. I'm running into a situation where iOS is killing the extension once hits 6MB of memory used.我正在编写一个 iOS 扩展,它在 iOS 9 中发布的NEPacketTunnelProvider框架中扩展了NEPacketTunnelProvider 。我遇到了一种情况,一旦达到 6MB 的内存使用量,iOS 就会终止扩展。

In a regular iOS app, there are two ways to detect memory warnings and do something about it.在常规的 iOS 应用程序中,有两种方法可以检测内存警告并对其采取措施。 Either via [UIApplicationDelegate applicationDidReceiveMemoryWarning:(UIApplication*)app] or [UIViewController didReceiveMemoryWarning]通过[UIApplicationDelegate applicationDidReceiveMemoryWarning:(UIApplication*)app][UIViewController didReceiveMemoryWarning]

Is there a similar way to detect memory warnings within an extension?是否有类似的方法来检测扩展中的内存警告? I've searched up and down the iOS extension documentation but have come up empty thus far.我已经上下搜索了 iOS 扩展文档,但到目前为止都是空的。

I am not very familiar with the extensions API, however my basic hunch says that you can register any of your object as observers of UIApplicationDidReceiveMemoryWarningNotification from within that class:我对扩展 API 不是很熟悉,但是我的基本预感是,您可以从该类中将您的任何对象注册为UIApplicationDidReceiveMemoryWarningNotification观察者:

NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidReceiveMemoryWarningNotification,
  object: nil, queue: .mainQueue()) { notification in
    print("Memory warning received")
}

ozgur's answer does not work. ozgur 的回答不起作用。 UIApplicationDidReceiveMemeoryWarningNotification is a UIKit event and I haven't found a way to get access to that from an extension. UIApplicationDidReceiveMemeoryWarningNotification 是一个 UIKit 事件,我还没有找到从扩展中访问它的方法。 The way to go is the last of these options : DISPATCH_SOURCE_TYPE_MEMORYPRESSURE.要走的路是这些选项中的最后一个:DISPATCH_SOURCE_TYPE_MEMORYPRESSURE。

I've used the following code (Swift) in a Broadcast Upload Extension and have confirmed with breakpoints that it is called during a memory event right before the extension conks out.我在广播上传扩展中使用了以下代码 (Swift),并通过断点确认它在扩展关闭之前的内存事件期间被调用。

let source = DispatchSource.makeMemoryPressureSource(eventMask: .all, queue: nil)

let q = DispatchQueue.init(label: "test")
q.async {
    source.setEventHandler {
        let event:DispatchSource.MemoryPressureEvent  = source.mask
        print(event)
        switch event {
        case DispatchSource.MemoryPressureEvent.normal:
            print("normal")
        case DispatchSource.MemoryPressureEvent.warning:
            print("warning")
        case DispatchSource.MemoryPressureEvent.critical:
            print("critical")
        default:
            break
        }
        
    }
    source.resume()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM