当前位置 : 主页 > 手机开发 > 其它 >

swift3 – FileManager replaceItemAt()导致EXC_BAD_ACCESS

来源:互联网 收集:自由互联 发布时间:2021-06-11
我写了一个从网站下载图像的应用程序. 如果设备上已存在此图像,我正在尝试更换它. func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let userId
我写了一个从网站下载图像的应用程序.
如果设备上已存在此图像,我正在尝试更换它.

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)
    }
}

我先调用copyItem.

网友评论