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

问题描述 投票:3回答:1

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

1-在哪里创建从Inbox到Document目录移动文件的方法?这是对的地方吗? 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个回答
6
投票

如果您的应用需要打开来自其他App的文件,则需要实现委托方法

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)
    NotificationCenter.default.post(name: .updateSort, object: destination)
} catch {
    print(error)
    return false
}

return true
© www.soinside.com 2019 - 2024. All rights reserved.