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

3
我正在编写一个iOS扩展,它扩展了iOS 9中发布的NetworkExtension框架中的NEPacketTunnelProvider。但我遇到了这样一种情况:一旦使用了6MB内存,iOS就会杀死这个扩展。
在常规的iOS应用程序中,有两种方法可以检测内存警告并采取行动。要么通过[UIApplicationDelegate applicationDidReceiveMemoryWarning:(UIApplication*)app],要么通过[UIViewController didReceiveMemoryWarning]。
在扩展中是否有类似的方法来检测内存警告?我已经在iOS扩展文档中进行了搜索,但迄今为止没有任何发现。
2个回答

5
ozgur的回答不可行。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()
}

-1

我对扩展API不是很熟悉,但我的基本直觉是你可以将任何对象注册为UIApplicationDidReceiveMemoryWarningNotification的观察者,从而在该类中实现:

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

1
@Grant Limberg @ozgur 我尝试使用NotificationServiceExtension,但是该块从未触发。即使传入新的 NSOperationQueue 以便该块能够在其自己的线程上运行。 - jkasten
2
我不知道为什么答案被标记为正确的,这是错误的!我们无法从扩展中访问“UIApplicationDidReceiveMemoryWarningNotification”。 - Ilya Muradymov
它不起作用;) 为什么它是正确的? - Bartłomiej Semańczyk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接