【问题标题】:Save file in folder将文件保存在文件夹中
【发布时间】:2017-08-24 13:45:28
【问题描述】:

我有ViewController 的单元格。如果用户单击其中一个单元格,他将使用 id(tableNumber) 进入下一个 TableController。在TableController 用户可以下载文件。

问题:当用户在第一个 tableView(id1) 中下载文件时返回 ViewController 并在下载后进入第二个 tableView(id2) 文件时保存在一个文件夹中,如下所示:/Documents/id2。但在这种情况下,我需要像这样保存文件:第一个文件/Documents/id1 第二个文件/Documents/id2。怎么做?

TableController 中的代码以在DownloadManager 中传递 id:

DownloadManager.shared.id = self.id

DownloadManager 中的代码保存文件:

var id = ""

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

        let fileName = downloadTask.originalRequest?.url?.lastPathComponent
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path[0]
        let fileManager = FileManager()
        var destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appending("/\(id)"))
        do {
            try fileManager.createDirectory(at: destinationURLForFile, withIntermediateDirectories: true, attributes: nil)
            destinationURLForFile.appendPathComponent(String(describing: fileName!))
            try fileManager.moveItem(at: location, to: destinationURLForFile)
        }catch(let error){
            print(error)
        }

    }

【问题讨论】:

  • @matt 我写这个有问题。我的文件保存在一个文件夹中。但是当用户下载多个文件时,我需要保存在两个文件夹中。
  • @matt 为什么要将一个文件夹保存在另一个文件夹中?我有 5 个表 ID?我需要将表中的文件保存到 5 个不同的文件夹(ID)中。当我从 5 个不同的表下载 5 个不同的文件时,这些文件仅保存到一个文件夹(最后一个 id)。但我需要保存在 5 个不同的文件夹中。

标签: ios swift


【解决方案1】:

对于每次下载,创建一个 DownloadManager 实例并下载视频。

您可以在 DownloadManager 中创建一个变量来保存文件夹路径、行/表 ID。

由于您为每次下载创建新的 DownloadManager 实例,您可以为每个视图控制器和行/表 ID 定义不同的文件夹路径。

文件下载后,使用上述变量将文件保存到文件夹中。

不要使用DownloadManager.shared.

使用DownloadManager()

希望这会有所帮助:)

【讨论】:

  • 我试图在全局变量中传递表 id,但这也不起作用。如果我使用这个var downloadManager = DownloadManager() 我会得到'DownloadManager' initializer is inaccessible due to 'private' protection level
  • 您的 DownloadManager init() 方法有 private 关键字。删除“私人”关键字。
  • 我使用:let downloadManager = DownloadManager() downloadManager.id = self.id 和 DownloadManager :var id = "" 但文件夹没有创建。
  • 为什么将 'id' 分配为空字符串?
  • var id = String() 但没有任何改变
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
相关资源
最近更新 更多