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

SwiftUI中PhotosPicker加载视频卡在加载阶段的问题求助

问题排查与修复方案

1. 补全错误日志,定位具体问题

你的错误捕获逻辑只输出了模糊提示,先修改成以下形式,获取精准错误信息:

catch {
    print("failed with ex: \(error.localizedDescription)")
    print("full error details: \(error)")
}

2. 修复废弃API,消除潜在隐患

URL.path()已被苹果废弃,替换为path属性:

if FileManager.default.fileExists(atPath: copy.path) {
    try FileManager.default.removeItem(at: copy)
}

3. 异步处理文件复制,解决大视频阻塞

当前同步复制大体积视频会直接卡住importing闭包,导致loadTransferable任务挂起无响应。改成后台异步处理:

static var transferRepresentation: some TransferRepresentation {
    FileRepresentation(contentType: .movie) { movie in
        SentTransferredFile(movie.url)
    } importing: { received in
        return try await Task.detached(priority: .background) {
            let copy = URL.documentsDirectory.appending(path: "movie.mp4")

            if FileManager.default.fileExists(atPath: copy.path) {
                try FileManager.default.removeItem(at: copy)
            }

            try FileManager.default.copyItem(at: received.file, to: copy)
            return Self.init(url: copy)
        }.value
    }
}

将复制逻辑放到后台任务中,避免阻塞主线程或loadTransferable的异步流程。

4. 扩展视频类型匹配,覆盖更多格式

.movie是通用类型,但部分相册视频可能使用更具体的UTI格式,直接指定多类型匹配:

FileRepresentation(contentType: [.movie, .mpeg4, .quickTimeMovie]) { movie in
    SentTransferredFile(movie.url)
} importing: { received in
    // ... 异步复制代码 ...
}

5. 添加临时日志,确认文件有效性

在importing闭包开头添加日志,验证系统传递的临时文件是否可访问:

importing: { received in
    print("Received temp file URL: \(received.file)")
    print("Temp file exists: \(FileManager.default.fileExists(atPath: received.file.path))")
    // ... 后续复制代码 ...
}

核心问题推测

你遇到的loadTransferable无返回问题,大概率是大视频同步复制阻塞了线程,导致整个异步任务卡在复制步骤。改成后台异步复制后,该问题基本可以解决;如果仍有异常,补全的错误日志会明确指向权限、路径或格式匹配等具体问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:50:58