【问题标题】:How to detect memory warnings in iOS App Extension如何检测 iOS App Extension 中的内存警告
【发布时间】:2015-12-08 04:31:20
【问题描述】:

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

在常规的 iOS 应用程序中,有两种方法可以检测内存警告并对其进行处理。通过[UIApplicationDelegate applicationDidReceiveMemoryWarning:(UIApplication*)app][UIViewController didReceiveMemoryWarning]

是否有类似的方法来检测扩展程序中的内存警告?我搜索了 iOS 扩展文档,但到目前为止都是空的。

【问题讨论】:

    标签: ios didreceivememorywarning ios-extensions networkextension


    【解决方案1】:

    ozgur 的回答不起作用。 UIApplicationDidReceiveMemeoryWarningNotification 是一个 UIKit 事件,我还没有找到从扩展中访问它的方法。要走的路是these options的最后一个: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()
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • @Grant Limberg @ozgur 我用 NotificationServiceExtension 尝试了这个,并且该块永远不会被触发。甚至传入一个新的NSOperationQueue 以便阻止它自己的线程上的火。
      • 我不知道为什么答案被标记为正确,这不是!我们无法从扩展访问“UIApplicationDidReceiveMemoryWarningNotification”。
      • 它不起作用;)为什么它是正确的?
      猜你喜欢
      • 1970-01-01
      • 2016-09-18
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2016-03-17
      • 2012-06-20
      相关资源
      最近更新 更多