Search code examples
iosswiftnsfilemanagerfile-manager

Is there a way to prevent NSFilemanger from exporting data and creating a folder?


Whenever the user exports data (it is a JSON format) it creates a folder named "Documents." And does not directly export the file and it does this for both my JSON export and CSV.

I have tried changing the fileManager settings but nothing seems to work that I have tried and that includes changing the default, for, and in. The latter two being when I call fileManger.url

Here is my main export for my JSON

// MARK: - Export to Share
    func toExportJSON() {
        // Call to clear Chached exported files
        clearAllFile()
        var exportArrayJson = [exportJsonData]()

        var exportArray = [Item]()
        exportArray = fetchedRC.fetchedObjects!

        for i in exportArray {

            let newI = exportJsonData(name: i.name!, pricePer: i.pricePer, totalPrice: i.totalPrice!, isComplete: i.isComplete, Qty: i.quantity, Cat: i.catagory!, Priority: i.priority, DNH: i.didHave)

            exportArrayJson.append(newI)
        }

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        encoder.keyEncodingStrategy = .convertToSnakeCase

        var jsonDataTop = Data()
        do {
            let jsonData = try encoder.encode(exportArrayJson)
            jsonDataTop = jsonData

        // Old Code to print for testing
        ///if let jsonString = String(data: jsonData, encoding: .utf8) {
            ///print(jsonString)
            ///print(jsonData)
        ///}

            let fileManager = FileManager.default
            do {

                let path = try fileManager.url(for: .documentDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
                let fileURL = path.appendingPathComponent("\(detailedList.lname!).json")
                try jsonDataTop.write(to: fileURL)//.write(to: fileURL)//write(to: fileURL, encoding: .utf8)

                let vc = UIActivityViewController(activityItems: [path], applicationActivities: [])

                present(vc, animated: true, completion: nil)
            } catch {
                print("error creating file")
            }
        } catch {
            print(error.localizedDescription)
        }
    }

I expect this to export the JSON by its self and not in a folder. I want only the file so it is easier for the user to share.


Solution

  • No matter where you save the file, you should delete it when the UIActivityViewController is finished. You can set a completion handler to remove the file.

    vc.completionWithItemsHandler = { (_, _, _, _) in
        try? fileManager.removeItem(at: fileURL)
    }
    

    Another option would be to save the file in the temporaryDirectory instead of documents.

    let fileURL = path
        .temporaryDirectory
        .appendingPathComponent("\(detailedList.lname!).json")
    

    But you should still remove the file after.