I am not an iOS developer, but I was asked to fix a bug in existing app.
There is a button to save the document from the server to files on the device.
A dialog window appears, you can select a directory and the file will be successfully saved.
But in the dialog window, the label above on the right is “Open”, but should be “Save”.
It is obvious that this is a system window and I can’t just take and change the text, but I saw that in other applications this inscription can be like “Save”
This code fragment is below.
#IBAction func download(_ sender: UIButton) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = .formSheet
present(documentPicker, animated: true, completion: nil)
}
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("documentPicker")
guard controller.documentPickerMode == .open, let url = urls.first else {
print("ERROR")
return
}
guard url.startAccessingSecurityScopedResource() else {
print("failed: startAccessingSecurityScopedResource()")
return
}
if self.downloadUrl.count > 0, self.downloadName.count > 0,
let downloadUrl = URL(string: self.downloadUrl){
// downloading
}
}
I tried to replace ".open" with other options, but it causes a crash.
Delegate method are not working for UIDocumentPickerViewController
from upload action want to load document from simulator for uploading to other action...
func uploadFile(){
let documentPickerController = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF), String(kUTTypeImage), String(kUTTypeMovie), String(kUTTypeVideo), String(kUTTypePlainText), String(kUTTypeMP3)], in: .import)
documentPickerController.delegate = self
present(documentPickerController, animated: true, completion: nil)
}
On selected didPickDocumentPicker noting happening in swift 5.0
extension UIViewController: UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate
{
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let myURL = urls.first else {
return
}
print("import result : \(myURL)")
let fileName = urls.first?.lastPathComponent
print(fileName)
// self.loadUploadView(selectedFile: fileName!)
}
func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("view was cancelled")
dismiss(animated: true, completion: nil)
}
}
For Device its working fine but for simulator its not working
else for iOS versions 13 its not working.
Device Version is 14
Simulator versions is 13.
I need to import to my app some document that have been saved into the "On My iPhone" folder. What would be the url of this folder? (those document (pdf) are saved outside the app by the user and I would like if possible to move/copy them to the app document folder but again I can't find that url.
Try this code (the way to pick needed document from iPhone Folder:
extension YourViewController: UIDocumentInteractionControllerDelegate {
/// If presenting a top a navigation stack, provide the navigation controller in order to animate in a manner consistent with the rest of the platform
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.navigationController ?? self
}
}
extension YourViewController : UIDocumentPickerDelegate {
func initDocs() {
let pickerController = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
pickerController.delegate = self
if #available(iOS 11.0, *) {
pickerController.allowsMultipleSelection = false
}
present(pickerController, animated: false, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if let url = urls.first {
self.handleDoc(url: url) // method in your view controller
}
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
print("url = \(url)")
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true, completion: nil)
}
}
In YourViewController call function:
#IBAction func importPem(_ sender: UIButton) {
initDocs()
UIDocumentInteractionController().presentPreview(animated: true)
}
I have integrated UIDocumentPickerDelegate or UIDocumentMenuDelegate, I have an issue to get the file from URL or DocumentPicker. How can I solve this issue in iOS swift?
You can get file easily like,
If you need to get image
#IBAction func btn_Handler_iCloud(_ sender: Any) {
let doc = UIDocumentMenuViewController(documentTypes: [String(kUTTypeImage)], in: .import)
doc.delegate = self
doc.modalPresentationStyle = .formSheet
self.present(doc, animated: true, completion: nil)
}
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
let data = try! Data(contentsOf: urls[0])
imageview_Buaty.image = UIImage.init(data: data)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
dismiss(animated: true, completion: nil)
}
Getting document URL or data from UIDocumentPickerViewController:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
// Available from iOS 8.0 to iOS 11.0
self.handleFileSelection(inUrl: url)// Here url is document's URL
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
// Available from iOS 11.0
self.handleFileSelection(inUrl: urls.first!) // Here urls is array of URLs
}
private func handleFileSelection(inUrl:URL) -> Void {
do {
// inUrl is the document's URL
let data = try Data(contentsOf: inUrl) // Getting file data here
} catch {
dLog(message: "document loading error")
}
}
I need to open UIDocumentPickerViewController and It should allow user to select all type of files. ie.(.pdf,.doc)files I used UIDocumentPickerViewController method.
my Code:
UIDocumentPickerDelegate, UIDocumentMenuDelegate in my class declaration
//upload file
func OpenFile(){
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePNG),String(kUTTypeImage)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .fullScreen
self.present(importMenu, animated: true, completion: nil)
}
#available(iOS 8.0, *)
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print("The Url is : \(cico)")
do {
let weatherData = try NSData(contentsOf: cico, options: NSData.ReadingOptions())
print(weatherData)
let activityItems = [weatherData]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
if UI_USER_INTERFACE_IDIOM() == .phone {
self.present(activityController, animated: true, completion: { _ in })
}
else {
let popup = UIPopoverController(contentViewController: activityController)
popup.present(from: CGRect(x: CGFloat(self.view.frame.size.width / 2), y: CGFloat(self.view.frame.size.height / 4), width: CGFloat(0), height: CGFloat(0)), in: self.view, permittedArrowDirections: .any, animated: true)
}
} catch {
print(error)
}
//optional, case PDF -> render
//displayPDFweb.loadRequest(NSURLRequest(url: cico) as URLRequest)
}
#available(iOS 8.0, *)
public func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print(" cancelled by user")
dismiss(animated: true, completion: nil)
}
In this code the app will crash. the reason is Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'You cannot initialize a UIDocumentPickerViewController except by the initWithDocumentTypes:inMode: and initWithURL:inMode: initializers.
I don't know how to initialise the initWithDocumentTypes:inMode. I'm new to iOS any one help me???
can you please help me..
Swift 3*, 4*,
To open document and select any document, you are using UIDocumentPickerViewController then all documents presented in your iCloud, Files and in Google Drive will be shown if Google Drive is connected in user device. Then selected document need to download in your app and from there you can show it in WKWebView,
#IBAction func uploadNewResumeAction(_ sender: Any) {
/* let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) */
let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text", "com.apple.iwork.pages.pages", "public.data"], in: .import)
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
extension YourViewController: UIDocumentPickerDelegate{
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print(cico)
print(url)
print(url.lastPathComponent)
print(url.pathExtension)
}
}
Note: If you intend to select all files the you have to use following code:
let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import)
In your action method.
To open the specific document files of (.pdf, .doc, .docx) using UIDocumentPickerViewController in Swift:
documentTypes would be
import import MobileCoreServices
["com.microsoft.word.doc","org.openxmlformats.wordprocessingml.document", kUTTypePDF as String]
Example:
let importMenu = UIDocumentPickerViewController(documentTypes: ["com.microsoft.word.doc","org.openxmlformats.wordprocessingml.document", kUTTypePDF as String], in: UIDocumentPickerMode.import)
importMenu.delegate = self
self.present(importMenu, animated: true, completion: nil)
Actually, instead of WebView you could also use the QuickLook
Framework, which is designed for this specific purpose. You just pass
the location of the file and conform to the protocols. It will present
a view controller with the document inside.
It supports the following file:
- iWork documents (Pages, Numbers and Keynote)
- Microsoft Office documents (as long as they’ve been created with Office 97 or any other newer version)
- PDF files
- Images
- Text files
- Rich-Text Format documents
- Comma-Separated Value files (csv)
Here is a tutorial by APPCODA, that describes the same.
and
Here is the tutorial provided by Apple OBJ-C version.