iOS , Copying files from Inbox folder to Document path

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-30 11:29:07

问题


I enabled Document Types to import or copy files from other apps to my application. I have some questions :

1- Where should create the method of moving files form Inbox to Document directory ? is this the right place ? func applicationWillEnterForeground(_ application: UIApplication)

2- On first view controller I am getting files from Document directory :

  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
        }

    }

But when a file imports to my app there is Inbox folder(item) in my table view , how can I automatically move files from Inbox to Document directory and remove Inbox folder ?


回答1:


If your app needs to open a file coming from another App you need to implement delegate method

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

and move the url to the folder of your choice inside your App.

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 ?? "")

Moving the file out of the inbox to your destination URL in your case the documents directory appending the 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


来源:https://stackoverflow.com/questions/46492353/ios-copying-files-from-inbox-folder-to-document-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!