我写了一个从网站下载图像的应用程序.
如果设备上已存在此图像,我正在尝试更换它.
如果设备上已存在此图像,我正在尝试更换它.
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,我找不到错误.
fileManager,target和location都是非零的.
我已经尝试将代码同步调度到主线程,但错误仍然存在.
有什么建议吗?
编辑:
由于我不是唯一一个遇到此错误的人,所以我决定在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) } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。