如何检测 iOS 应用扩展中的内存警告

Gra*_*erg 4 didreceivememorywarning ios ios-extensions networkextension

我正在编写一个在 iOS 9 中发布的 NetworkExtension 框架中扩展的 iOS 扩展。NEPacketTunnelProvider我遇到了这样的情况:一旦使用的内存达到 6MB,iOS 就会终止该扩展。

在常规 iOS 应用程序中,有两种方法可以检测内存警告并采取措施。通过[UIApplicationDelegate applicationDidReceiveMemoryWarning:(UIApplication*)app][UIViewController didReceiveMemoryWarning]

是否有类似的方法来检测扩展中的内存警告?我已经搜索了 iOS 扩展文档,但到目前为止一无所获。

小智 5

奥兹古尔的回答不起作用。UIApplicationDidReceiveMemeoryWarningNotification 是一个 UIKit 事件,我还没有找到从扩展程序访问该事件的方法。要走的路是这些选项中的最后一个:DISPATCH_SOURCE_TYPE_MEMORYPRESSURE。

我在广播上传扩展中使用了以下代码(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()
}
Run Code Online (Sandbox Code Playgroud)