How to open the Document files e.g(.pdf,.doc,.docx) in ios mobile when a button action using swift3.0?

45.6k views Asked by At

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..

4

There are 4 answers

18
Abhishek Mitra On BEST ANSWER

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.

2
Umar Farooque On

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.

2
Himanshu padia On

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)
2
Breiby On

UIDocumentPickerViewController.init(documentTypes:in:) and kUTType___ were deprecated in iOS 14 and 15 respectively. Here's how to achieve the same on newer versions of iOS:

let contentTypes: [UTType] = [
    .init(filenameExtension: "doc")!,
    .init(filenameExtension: "docx")!,
    .pdf
]

let documentPicker = UIDocumentPickerViewController.init(forOpeningContentTypes: contentTypes, asCopy: true)
documentPicker.delegate = self
present(documentPicker, animated: true)