我正在使用 SwiftUI 构建我的第一个 iOS 应用程序,并尝试在小部件中显示图像。这在大多数情况下都有效,但有时图像不会渲染,即使它过去已经可以显示它们。这似乎完全是任意的。我想说它在 95% 的情况下有效,但在 5% 的情况下失败(我每小时刷新一次小部件)。
现在我已经收集了一些日志,但我找不到有关错误的有用信息:
standard 06:39:45.111861+0200 WidgetsExtension container_create_or_lookup_app_group_path_by_app_group_identifier: success
fehler 06:39:45.124706+0200 WidgetsExtension CreateWithURL:342: *** ERROR: err=1 (Operation not permitted) - could not open '<CFURL 0x102346d60 [0x1f78674f8]>{string = file:///private/var/mobile/Containers/Shared/AppGroup/DBD07167-ED05-4BDF-A302-5173C84F0717/5230A437-503C-430E-A808-4AEF47D4D1B9-systemSmall.jpg, encoding = 134217984, base = (null)}'
fehler 06:39:45.126538+0200 WidgetsExtension createImageAtIndex:1869: *** ERROR: could not find plugin for image source - imageRead is NULL
fehler 06:39:45.126574+0200 WidgetsExtension createImageAtIndex:2007: *** ERROR: createImageAtIndex[0] - 'n/a ' - failed to create image [-62]
fehler 06:39:45.126601+0200 WidgetsExtension CGImageSourceCreateImageAtIndex:4984: *** ERROR: CGImageSourceCreateImageAtIndex[0] - 'n/a ' - failed to create image [-62]
这就是我尝试加载图像的方式(这里也提供源代码):
struct HighlightsTile: View {
var highlight: Moment
var photoImage: UIImage?
init(highlights: [Moment], size: ImageSize) {
self.highlight = highlights[0]
if highlight.photo != nil {
let photoUrl = FileManager.documentsDirectory.appendingPathComponent("\(String(describing: highlight.photo!))-\(size).jpg")
self.photoImage = UIImage(contentsOfFile: photoUrl.path)
}
}
}
我发现您收到的第一个错误与文件未打开有关。我发现的一种代码味道可能是使用
String(describing: highlight.photo)
使用此初始值设定项将任何类型的实例转换为其首选的 String 实例表示形式。
您的highlight.photo符合CustomStringConvertible吗?
您应该使用
.appendingPathComponent()
并提供准确的文件名,而不是“描述”它