UIDocumentInteractionController can't open CSV file in SwiftUI

58 views Asked by At

I am trying to open written CSV file, in outside my app that is user chooses. I have tried to do it with this code:

  if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            
            var fileURL: URL
            
            if #available(iOS 16.0, *) {
                fileURL = documentsDirectory.appending(path: "\(fileName).csv")
            } else {
                // Fallback on earlier versions
                fileURL = documentsDirectory.appendingPathComponent("\(fileName).csv")
            }
            
            do {
                try csvData.write(to: fileURL, atomically: true, encoding: .utf8)
                print("writeCSVFile(): Writed new file '\(fileName)', on path: \(fileURL)")

                
                let documentController = UIDocumentInteractionController(url: fileURL)
                documentController.delegate = UIApplication.shared.delegate as? UIDocumentInteractionControllerDelegate
                
                if !documentController.presentOpenInMenu(from: CGRect.zero, in: self.viewController.view, animated: true) {
                   print("MyTest(): Failed")
                }
            } catch {
                print("writeCSVFile(): Failed to write file on path: \(fileURL). \(error)")
                alertTitle = "Failed to create new file"
                alertMessage = "New file creation failed"
                showAlert = true
            }
        } else {
            alertTitle = "Failed to create new file"
            alertMessage = "New file creation failed"
            showAlert = true
        }

And I have created the viewController like this:

    var viewController: UIViewController {
        UIApplication.shared.windows.first!.rootViewController!
    }

The menu opens that lets user choose the app to open with, but it does not actually do anything. It allows user to send the file to Reminders, Notes or Save to Files. But when Save to Files is clicked nothing actually happen. The file is not located on Files and even the files app is not opened, it only flashes white screen for 2 seconds.

When Save to files is clicked this shows up in the console:

[ShareSheet] cancelled request - error: The operation couldn’t be completed. Invalid argument

I have checked that there should not be any errors on the console indigating that file creation would be failed.

0

There are 0 answers