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

iOS应用崩溃排查:NSInternalInconsistencyException异常问题

问题分析与解决方案

崩溃原因

你的崩溃是因为PHPhotoLibrary的performChanges完成回调默认在后台线程执行,而你在if completed {}里调用的removeAllOverlays()涉及UI布局修改——iOS要求所有UI操作必须在主线程执行,因此触发了NSInternalInconsistencyException异常。

修复代码

把回调里的UI操作切回主线程即可,修改后的代码如下:

func downloadVideoLinkAndCreateAsset(videoLink: String?) {
    
    DispatchQueue.global(qos: .background).async {
        guard let url = URL(string: videoLink ?? ""),
              let urlData = NSData(contentsOf: url) else {
            return
        }
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/tempFile.mp4"
        
        DispatchQueue.main.async {
            urlData.write(toFile: filePath, atomically: true)
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
            }) { completed, error in
                // 将UI操作切回主线程
                DispatchQueue.main.async {
                    if completed {
                        self.removeAllOverlays()
                        print("Video is Saved in Library")
                    }
                    // 补充错误处理
                    if let error = error {
                        print("保存视频失败: \(error.localizedDescription)")
                    }
                }
            }
        }
    }
}

额外优化建议

  1. 替换NSData(contentsOf: url):这是同步下载方法,虽在后台线程,但网络差时会阻塞线程,建议用URLSession异步下载,避免线程长时间占用。
  2. 临时文件清理:视频保存到相册成功后,记得删除tempFile.mp4,避免浪费存储空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:20:51