You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI PhotosPicker加载Transferable图片失败求助

问题描述

以下代码在新应用中运行正常,但在现有应用中始终失败,抛出importNotSupported错误,同时出现权限相关报错(无法访问CoordinatedZipFilep40sph,操作未被允许),该问题在未沙箱的macOS和iOS上均存在。

补充信息:GIF和PNG可被正常获取,但JPEG、HEIC等格式均加载失败。

代码示例:

@State private var isShowingPhotoPicker = false
@State private var selectedItem: PhotosPickerItem? = nil
Button("Select image") {
      isShowingPhotoPicker.toggle()
}
.photosPicker(isPresented: $isShowingPhotoPicker, selection: $selectedItem, matching: .images, photoLibrary: .shared())
.onChange(of: selectedItem) { newItem in
                if let newItem {
                    Task {
                        do {
                            if let image = try await newItem.loadTransferable(type: NSImage.self) {
                               //Do something with the image....
                            }
                        } catch {
                            NSLog("\(error)")
                        }
                    }
                }
            }
问题原因与解决办法
  • 核心原因:现有应用的Info.plist中缺失JPEG、HEIC等格式的UTI(统一类型标识符)声明,系统无法识别这些格式并允许应用加载,而PNG、GIF的UTI已在应用中提前配置。
  • 规范解决步骤:
    1. 打开应用的Info.plist文件。
    2. 添加LSItemContentTypes数组(若不存在则新建),在数组中添加对应格式的UTI:
      • JPEG:public.jpeg
      • HEIC:public.heic
      • 如需额外格式,可补充public.heif(HEIF)等。
    3. 保存文件后重新编译运行应用。
  • 临时替代方案:若不想修改Info.plist,可先加载原始Data类型,再转换为图片:
    if let data = try await newItem.loadTransferable(type: Data.self) {
        if let image = NSImage(data: data) {
            // 处理图片逻辑
        }
    }
    

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:58:14