0

I am working on a file download currently. After the download is finished I want to move the downloaded file to the apps document directory, my setup:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    debugPrint("didFinishDownloadingTo: \(location)")

    let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let saveDirectory = documentsDirectory.appendingPathComponent("file1.mp4")

    do {
        try FileManager.default.moveItem(at: location, to: saveDirectory)
    } catch {
        print("didFinishDownloadingTo error \(error.localizedDescription)")
    }
}

At some point I want to see all my downloaded files:

do {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = String(describing: paths[0])

    let items = try FileManager.default.contentsOfDirectory(atPath: documentsDirectory)

    for item in items {
        print("Found \(item)")
    }
} catch {
    print("contentsOfDirectory \(error.localizedDescription)")
}

This part throws:

The folder “Documents” doesn’t exist.

The didFinishDownloadingTo method throws no error, so I assume the moveitem function succeeded, but I have no idea why I cant list my items... I did some research, but with no result and I dont know why I can't list.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Creative crypter
  • 1,348
  • 6
  • 30
  • 67
  • 1
    Don't use `String(describing:)` method. It will return your url `absoluteString` which includes the "file://" prefix (url scheme). Just use your document directory url path property. `FileManager.default.contentsOfDirectory(atPath: paths.first!.path)` – Leo Dabus Nov 26 '17 at 15:31

1 Answers1

0

Try debugging by simply printing the paths and check those folders. This way you can see which step is not working as expected. I think there is a small mistake with paths which might be easier to catch while debugging.

Tip: debug using simulator but not a real device. Since it will make it much easier just to navigate through the folders.

Hope it helps.

Tung Fam
  • 7,899
  • 4
  • 56
  • 63