iOS,将文件从收件箱文件夹复制到文档路径

标签 ios iphone swift nsfilemanager

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

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

2- 在第一个 View Controller 上,我从文档目录获取文件:

  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
        }

    }

但是当文件导入到我的应用程序时,我的 TableView 中有 Inbox 文件夹(项目),我如何自动将文件从 Inbox 移动到 Document 目录并删除收件箱文件夹?

最佳答案

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

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

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

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

关于iOS,将文件从收件箱文件夹复制到文档路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46492353/

相关文章:

iphone - 蓝牙连接到其他没有附件的外部 USB 蓝牙设备?

objective-c - UITableView 以编程方式选择选项

ios - 如何将谷歌地图路线导入 Sygic iOS App?

ios - 是否可以在 scrollToItemAtIndexPath 方法的 atScrollPosition 参数中添加边距?

swift - LaunchImage 和 TabBarViewController 之间显示的银色背景

ios - Swift 打印 anchor 常量值

ios - Swift UIViewController Custom init() - 错误无法分配给自己

ios - Swift 符合协议(protocol)子类

iphone - 核心数据 NSFetchedResultsController - 返回的记录总数

iphone - 从 NSUserDefaults 中检索 PSMultiValueSpecifier 字符串