在使用PhotosPicker时,来自iOS照片库的itemIdentifier为 nil

移动开发 2026-07-10

我正在把一款用Objective-C和 OpenGL编写的较旧的Mac应用更新成一款跨平台应用,使用SwiftUI与 Metal。

该应用会加载图像,并据此生成万花筒动画。

它是一个基于文档的应用,将万花筒的相关信息保存在文档中。在macOS上,它会创建一个安全作用域书签,以记住用户选择的图片。

在iOS上,我使用PhotosPicker让用户从照片库中选择一张图片以供使用。我想从他们选择的图片中获取 itemIdentifier 并将其保存到我的文档中,这样在用户将来重新打开万花筒文档时就可以用它来获取该图片。

然而,对 loadTransferable 的调用在 itemIdentifier 上返回nil。以下是我的iOS/iPadOS代码:

#if os(macOS)
    // Mac code
#else
    PhotosPicker("Choose image", selection: $selectedItem, matching: .images)
        .onChange(of: selectedItem) {
            Task {
                if let newValue = selectedItem {
                    scopeState.isHEIC =  newValue.supportedContentTypes.contains(UTType.heic)

                    let data = try? await newValue.loadTransferable(type: Data.self)
                    print("newValue = \(newValue)")
                    print("newValue.supportedContentTypes = \(newValue.supportedContentTypes)")
                    scopeState.selectedImageID = newValue.itemIdentifier
                    scopeState.selectedImageData = data
                }
            }
        }
#endif

调试输出如下:

newValue = PhotosPickerItem(_itemIdentifier: "9386762B-C241-4EE2-9942-BC04017E35C1/L0/001", _shouldExposeItemIdentifier: false, _supportedContentTypes: [<_UTCoreType 0x20098cd40> public.png (not dynamic, declared), <UTType 0x11e4ec060> com.apple.private.photos.thumbnail.standard (not dynamic, declared), <UTType 0x11e4ec150> com.apple.private.photos.thumbnail.low (not dynamic, declared)], _content: _PhotosUI_SwiftUI.PhotosPickerItem.(unknown context at $1e75ee3bc).Content.result(PhotosUI.PHPickerResult(itemProvider: <PUPhotosFileProviderItemProvider: 0x11d2bd680> {types = (
    "public.png",
    "com.apple.private.photos.thumbnail.standard",
    "com.apple.private.photos.thumbnail.low"
)}, _objcResult: <PHPickerResult: 0x11b18cff0>)))
newValue.supportedContentTypes = [<_UTCoreType 0x20098cd40> public.png (not dynamic, declared), <UTType 0x11e4ec060> com.apple.private.photos.thumbnail.standard (not dynamic, declared), <UTType 0x11e4ec150> com.apple.private.photos.thumbnail.low (not dynamic, declared)]

返回的项的itemIdentifier为 nil。(请注意所选项日志中的 _shouldExposeItemIdentifier=false。)

如何获取用户所选图片的itemIdentifier?

那么在用户重新加载文档时,是否可以据此获取资源?它是否类似于macOS上的安全作用域书签,其中的 itemIdentifier 就像一个钥匙,能让我重新加载图片的权限?

如果不是,那么为了在用户下次打开保存的万花筒文档时重新加载图片,我需要做什么?

解决方案

根据文档,你需要一个库

let library: PHPhotoLibrary = .shared()

并将其添加到 init

PhotosPicker(selection: $selectedItem, photoLibrary: library) {

你可以查看一个工作示例 SwiftUI PhotosPicker - 获取所选项大小(以千字节为单位)

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章