Alamofire iOS - 在下载期间指定不是临时目录的位置

Alamofire iOS - specify during-download location that isn't temp directory

我知道 Alamofire (iOS) 允许指定下载目的地,但文件会保留在临时目录中,直到下载完成。我们希望能够在此过程中将文件放在文档目录中(并在下载完成后保留在那里)。

有谁知道这是否可行?

谢谢

是,指定下载位置URL

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendPathComponent("pig.png")

    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}

Alamofire.download(urlString, to: destination).response { response in
    print(response)

    if response.result.isSuccess, let imagePath = response.destinationURL?.path {
        let image = UIImage(contentsOfFile: imagePath)
    }
}

根据需要更改文档目录路径

我无法通过下载任务完成此操作。 Alamofire 本质上包装了 URLSession,Alamofire.download 包装了 URLSessionDownloadTask,我已经尝试在 Alamofire 之外使用它。该文件在完成之前不会放置在您的下载目标中。

为了暂时完成此操作,我不得不使用 URLSessionDataTask,并使用 am OutputStream/NSOutputStream 将数据逐块写入文件,该文件会反复打开和关闭,以便刷新,并且可以在完成之前阅读。这就是我想要完成的,它似乎有效,而且速度足够快。