SwiftUI:应用程序在从后台返回后激活显示时崩溃

SwiftUI: App crashes on activation of display after returning from the background

该应用程序在前台运行良好。动画有效,音频播放没有问题(甚至来自通知)。 但是,在应用程序进入后台后,过了一会儿,应用程序崩溃并出现以下错误:

    Exception Type:  EXC_BAD_ACCESS ()
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016b45fff0
VM Region Info: 0x16b45fff0 is in 0x16b45c000-0x16b460000;  bytes after start: 16368  bytes before end: 15
      REGION TYPE                 START - END      [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      CoreAnimation            11edd0000-11f860000 [ 10.6M] rw-/rwx SM=PRV  
      GAP OF 0x4bbfc000 BYTES
--->  STACK GUARD              16b45c000-16b460000 [   16K] ---/rwx SM=NUL  ... for thread 0
      Stack                    16b460000-16b55c000 [ 1008K] rw-/rwx SM=PRV  thread 0

Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [7134]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   libswiftCore.dylib              0x000000018d84f360 swift::MetadataCacheKey::operator==(swift::MetadataCacheKey) const + 4 (MetadataCache.h:457)
1   libswiftCore.dylib              0x000000018d84f5c0 std::__1::pair<swift::HashMapElementWrapper<(anonymous namespace)::GenericCacheEntry>*, unsigned int> swift::ConcurrentReadableHashMap<swift::HashMapElementWrapper<(anonymous namespace)::GenericCac... + 272 (MetadataCache.h:1439)
2   libswiftCore.dylib              0x000000018d841bd8 _swift_getGenericMetadata(swift::MetadataRequest, void const* const*, swift::TargetTypeContextDescriptor<swift::InProcess> const*) + 380 (Concurrent.h:1001)
3   libswiftCore.dylib              0x000000018d822d00 __swift_instantiateCanonicalPrespecializedGenericMetadata + 36 (<compiler-generated>:0)
4   SwiftUI                         0x00000001909499a8 AnimatorBox.value(in:for:) + 140 (Animation.swift:167)
5   SwiftUI                         0x0000000190948454 AnyAnimator.value(in:for:) + 140 (Animation.swift:116)
6   SwiftUI                         0x00000001907d548c DefaultCombiningAnimator.value(in:for:) + 716 (DefaultCombiningAnimation.swift:26)

我个人认为这与音频的关系比任何动画都大,但是,错误堆栈并没有太大帮助。另一个问题是,我不能说应用程序是否已经在后台崩溃,或者只是在显示屏亮起并且应用程序准备 return 进入前台时崩溃。

有人遇到过这个错误吗?是什么原因造成的? Animation.swift 是一个系统文件,我无法将问题追溯到我的代码。

欢迎提出任何建议。谢谢

所以我会post回答这个问题,因为它可能会帮助将来遇到类似问题的人。

事实证明,问题确实出在动画上。

在我的大部分代码中,我使用了以下实例方法:

func animation(_ animation: Animation?) -> some View

顺便说一句。显然将在 iOS 15 中弃用。来源:Apple 文档

问题在于,每次重新加载视图时,所有视图都会进行动画处理,无论它们是否应该进行动画处理。我个人的猜测是这在后台引起了一些并发问题。

无论如何,解决方案应该是这样的

func animation<V>(_ animation: Animation?, value: V) -> some View where V : Equatable

其中值为:

A value to monitor for changes.

使用此方法,如果您正确配置视图,即使 运行 在后台,当监控值发生变化时,视图也会动画化。

我希望这会对某人有所帮助。这绝对解决了我的问题!