Swift3 FileManager replaceItemAt()导致EXC\u错误访问
我编写了一个从网站下载图像的应用程序。 如果设备上已经存在此映像,我将尝试替换它Swift3 FileManager replaceItemAt()导致EXC\u错误访问,swift3,exc-bad-access,ios10,nsfilemanager,Swift3,Exc Bad Access,Ios10,Nsfilemanager,我编写了一个从网站下载图像的应用程序。 如果设备上已经存在此映像,我将尝试替换它 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let userId = Int.init(downloadTask.taskDescription!)! // task description is definetly s
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\u BAD\u访问
,但我找不到错误。
文件管理器
、目标
和位置
为非零。
我已经尝试将代码同步分派到主线程,但错误仍然存在
有什么建议吗
编辑:
因为我不是唯一一个犯这个错误的人,所以我决定在苹果公司创建一个bug报告。
该报告可在Open Radar上获得
我还上传了一个示例,演示了错误,并提供了一个类似的快速解决方案。在下载完成并发布了
文件管理器时,持有此方法的类已不存在。在完成闭包中创建FileManager
:
...
let localFilemanager = FileManager.default
do {
...
有同样的问题。最后写了我自己的版本:
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打电话。我已经试过了。例外情况仍然存在。此外,if语句的布尔求值也可以正常工作。该变量在调用时存在。在if
子句中,打印fileManager
、target
和location
,以找出故障制造者。然后,请用您已经尝试过的内容、这些尝试的结果(日志)和确切的错误(地址)更新您的问题没有建议,但我在我的项目中也面临着完全相同的问题。这一次不在关闭范围内。像你一样,我要么更换,要么移动物品。移动操作可以工作,但是替换总是会失败,因为EXC_访问错误。我已经创建了一个错误报告,似乎在Xcode版本8.2(8C38)中得到了修复。