swift3 – FileManager replaceItemAt()导致EXC_BAD_ACCESS
发布时间:2020-12-14 04:34:29 所属栏目:百科 来源:网络整理
导读:我写了一个从网站下载图像的应用程序. 如果设备上已存在此图像,我正在尝试更换它. func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didFinishDownloadingTo location: URL) { let userId = Int.init(downloadTask.taskDescript
我写了一个从网站下载图像的应用程序.
如果设备上已存在此图像,我正在尝试更换它. 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,我找不到错误. 有什么建议吗? 编辑: 由于我不是唯一一个遇到此错误的人,所以我决定在Apple创建一个错误报告. 我还上传了一个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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |