swift 从主线程访问布局引擎后,不能从后台线程执行对布局引擎的修改,”

qyyhg6bp  于 2022-11-28  发布在  Swift
关注(0)|答案(1)|浏览(123)

我的应用程序崩溃“由于未捕获的异常”NSInternalInconsistencyException“,正在终止应用程序,原因:'从主线程访问布局引擎后,不能从后台线程执行对布局引擎的修改。”
我从网址下载一个mp4文件,当它成功地将文件保存在库中时,它在打印消息时崩溃。

Code crashes after if completed { }

func downloadVideoLinkAndCreateAsset(videoLink: String?) {
    
    DispatchQueue.global(qos: .background).async {
        if let url = URL(string: videoLink ?? ""),
           let urlData = NSData(contentsOf: url) {
            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
                    if completed {
                        self.removeAllOverlays()
                        print( "Video is Saved in Library")
                    }
                }
            }
        }
    }
    
    
}
exdqitrt

exdqitrt1#

这句话的意思是
“照片”在任意串行队列上执行更改块和完成处理程序块。若要因更改而更新应用的UI,请将该工作分派到主队列。
因此,在performChanges闭包中,执行UI更新的DispatchQueue.main.async
因此,应改为:

DispatchQueue.main.async {
    urlData.write(toFile: filePath, atomically: true)
    PHPhotoLibrary.shared().performChanges {
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
    } completionHandler: { completed, error in
        if completed {
            self.removeAllOverlays()
            print( "Video is Saved in Library")
        }
    }
}

您需要:

urlData.write(toFile: filePath, atomically: true)
PHPhotoLibrary.shared().performChanges {
    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
} completionHandler: { completed, error in
    if completed {
        DispatchQueue.main.async {
            self.removeAllOverlays()
        }
        print( "Video is Saved in Library")
    }
}

相关问题