【问题标题】:iOS , Copying files from Inbox folder to Document pathiOS,将文件从收件箱文件夹复制到文档路径
【发布时间】:2018-03-11 13:36:48
【问题描述】:

我启用了文档类型以将文件从其他应用程序导入或复制到我的应用程序。我有一些问题:

1- 应该在哪里创建将文件从收件箱移动到文档目录的方法?这是正确的地方吗? func applicationWillEnterForeground(_ application: UIApplication)

2- 在第一个视图控制器上,我从 Document 目录获取文件:

  func getFileListByDate() -> [String]? {

        let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        if let urlArray = try? FileManager.default.contentsOfDirectory(at: directory,
                                                                       includingPropertiesForKeys: [.contentModificationDateKey],
                                                                       options:.skipsHiddenFiles) {

            return urlArray.map { url in
                (url.lastPathComponent, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast)
                }
                .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
                .map { $0.0 } // extract file names

        } else {
            return nil
        }

    }

但是当文件导入到我的应用程序时,我的表格视图中有Inbox 文件夹(项目),我怎样才能自动将文件从Inbox 移动到Document 目录并删除收件箱文件夹?

【问题讨论】:

  • 你的问题不是很清楚。能说清楚吗?

标签: ios iphone swift nsfilemanager


【解决方案1】:

如果您的应用需要打开来自另一个应用的文件,您需要实现委托方法

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

并将网址移动到您在应用程序中选择的文件夹。

let url = url.standardizedFileURL  // this will strip out the private from your url
// if you need to know which app is sending the file or decide if you will open in place or not you need to check the options  
let openInPlace = options[.openInPlace] as? Bool == true
let sourceApplication = options[.sourceApplication] as? String
let annotation = options[.annotation] as? [String: Any]
// checking the options info
print("openInPlace:", openInPlace)
print("sourceApplication:", sourceApplication ?? "")
print("annotation:", annotation ?? "")

将文件从收件箱移出到您的目标 URL,在您的情况下是附加 url.lastPathComponent 的文档目录:

do {
    try FileManager.default.moveItem(at: url, to: destinationURL)
    print(url.path)
    print("file moved from:", url, "to:", destinationURL)

} catch {
    print(error)
    return false
}

return true

【讨论】:

  • 谢谢,我会试试的,但一个问题是如何删除收件箱文件夹?
  • @Mc.Lover 你不能。但这并不意味着您需要将其展示给用户。您可以在显示数组之前对其进行过滤
  • 那么有什么办法可以隐藏吗?因为我通过这种方法 getFileListByDate 从 Documents 文件夹中获取文件,这显示了我只需要显示文件的文件夹和文件
  • 如果您只需要显示文件,只需过滤所有目录的 url
  • 我看不到您如何使用您的方法返回的字符串。如果计数无关紧要,只需过滤!=“收件箱”stackoverflow.com/questions/27878798/…
猜你喜欢
  • 1970-01-01
  • 2020-08-15
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
相关资源
最近更新 更多