So in my app I have created a Test.JSON file that I want the user to be able to move to the documents directory, outside of the app. I understand I have to do this by using UIDocumentPickerViewController
, but haven’t found any way to proceed. I have created the Test.JSON file, and can use it from variable data
.
I have this following code to open the UIDocumentPickerViewController
:
let documentPicker =
UIDocumentPickerViewController(forExporting: [.documentsDirectory])
documentPicker.delegate = self
// Set the initial directory.
documentPicker.directoryURL = .documentsDirectory
// Present the document picker.
present(documentPicker, animated: true, completion: nil)
How can I attach the data file to the UIDocumentPickerViewController
, so I can place it in the documents directory?
2
Answers
Have you followed the instructions that Apple provides here? I’m summarizing the important bits here:
So first, you need to implement the delegate methods so that you know what the user selects. Specifically,
documentPicker(_:didPickDocumentsAt:)
is the important one, although you’ll want to listen for "cancel" as well. Then you need to access that scoped resource and write to it.Here is an example that I took from the documentation linked above. This example only reads from the directory, but you can also write to it in the same way.
If you already have the URL for the document replace ‘newFile’ with the document URL. ‘vc’ is the current ViewController
Note asCopy = false will move the the document, asCopy = true will copy the document.
There appears to be bug in iOS 16+ which disables the Move button when asCopy = false.Bug fixed in subsequent release FB11627056