Search code examples
iosiphoneswiftnsfilemanager

iOS , Copying files from Inbox folder to Document path


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 ?


Solution

  • 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