gpt4 book ai didi

swift3 - FileManager ReplaceItemAt() 导致 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-12-01 18:00:28 25 4
gpt4 key购买 nike

我编写了一个从网站下载图像的应用程序。如果该图像已存在于设备上,我将尝试替换它。

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let userId = Int.init(downloadTask.taskDescription!)! // task description is definetly set in downloadImage() and is an Int
guard let target = imageFolder?.appendingPathComponent("\(userId).jpg") else {
delegate?.imageDownloadFailed(forUser: userId, error: "Could not create target URL.")
return
}

do {
if fileManager.fileExists(atPath: target.path) {
_ = try fileManager.replaceItemAt(target, withItemAt: location)
} else {
try fileManager.moveItem(at: location, to: target)
}
delegate?.savedImage(forUser: userId, at: target)
} catch let error {
delegate?.imageDownloadFailed(forUser: userId, error: error.localizedDescription)
}
}

问题出现在 if 语句中:

_ = try fileManager.replaceItemAt(target, withItemAt: location)

我总是遇到EXC_BAD_ACCESS,但找不到错误。fileManagertargetlocation 均非零。我已经尝试将代码同步分派(dispatch)到主线程,但错误仍然存​​在。

有什么建议吗?

编辑:

由于我不是唯一遇到此错误的人,因此我决定在 Apple 创建一份错误报告。该报告可在 Open Radar 上获取; click

我还上传了 playground file at pastebin.com它演示了错误并提供了类似于 naudec 的快速解决方案.

最佳答案

有同样的问题。最终编写了我自己的版本:

let fileManager = FileManager.default

func copyItem(at srcURL: URL, to dstURL: URL) {
do {
try fileManager.copyItem(at: srcURL, to: dstURL)
} catch let error as NSError {
if error.code == NSFileWriteFileExistsError {
print("File exists. Trying to replace")
replaceItem(at: dstURL, with: srcURL)
}
}
}

func replaceItem(at dstURL: URL, with srcURL: URL) {
do {
try fileManager.removeItem(at: dstURL)
copyItem(at: srcURL, to: dstURL)
} catch let error as NSError {
print(error.localizedDescription)
}
}

我首先调用copyItem

关于swift3 - FileManager ReplaceItemAt() 导致 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com