FileManager replaceItemAt () results in EXC_BAD_ACCESS

I wrote an application that downloads images from a website. If this image already exists on the device, I am trying to replace it.

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

The problem occurs in if-statement:

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

I always got EXC_BAD_ACCESSand I can not find the error. fileManager, targetand are locationnot equal to zero. I already tried to send the code synchronously to the main thread, but the error still persists.

Any tips?

Edit:

Since I'm not the only one who got this error, I decided to create an error report in Apple. The report is available in open radar; click

pastebin.com, , , a href= "/questions/1657129/filemanager-replaceitemat-results-in-excbadaccess/4844444#4844444" > naudec.

+4
2

. :

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.

+3

, , filemanager. filemanager :

...
let localFilemanager = FileManager.default
do {
...
0

Source: https://habr.com/ru/post/1657129/


All Articles