ios 当使用swift3.0的按钮动作时,如何在ios mobile中打开文档文件eg(.pdf,.doc,.docx)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47865646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:39:20  来源:igfitidea点击:

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

iosswift3documentuidocumentuidocumentmenuvc

提问by mouni

I need to open UIDocumentPickerViewControllerand It should allow user to select all type of files. ie.(.pdf,.doc)files I used UIDocumentPickerViewControllermethod. my Code:

我需要打开UIDocumentPickerViewController它应该允许用户选择所有类型的文件。ie.(.pdf,.doc) 文件我使用的UIDocumentPickerViewController方法。我的代码:

UIDocumentPickerDelegate, UIDocumentMenuDelegatein my class declaration

UIDocumentPickerDelegate, UIDocumentMenuDelegate在我的班级声明中

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

在此代码中,应用程序将崩溃。原因是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..

我不知道如何初始化initWithDocumentTypes:inMode.我是 iOS 新手,有人帮我吗???你能帮我么..

回答by Abhishek Mitra

Swift 3*, 4*,

斯威夫特 3*, 4*,

To open document and select any document, you are using UIDocumentPickerViewControllerthen 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,

要打开文档并选择任何文档,您正在使用UIDocumentPickerViewControlleriCloud、文件和 Google Drive 中显示的所有文档,如果用户设备中连接了 Google Drive。然后需要在您的应用程序中下载选定的文档,然后您可以在其中显示它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.

在你的行动方法中。

回答by Umar Farooque

Actually, instead of WebViewyou could also use the QuickLookFramework, 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.

实际上,您还可以使用专为此特定目的而设计的QuickLook Framework来代替WebView。您只需传递文件的位置并符合协议。它将呈现一个带有文档的视图控制器。

It supports the following file:

它支持以下文件:

- iWork documents (Pages, Numbers and Keynote)

- iWork 文档(Pages、Numbers 和 Keynote)

- Microsoft Office documents (as long as they've been created with Office 97 or any other newer version)

- Microsoft Office 文档(只要它们是使用 Office 97 或任何其他更新版本创建的)

- PDF files

- PDF 文件

- Images

- 图片

- Text files

- 文本文件

- Rich-Text Format documents

- 富文本格式文档

- Comma-Separated Value files (csv)

- 逗号分隔值文件 (csv)

Hereis a tutorial by APPCODA, that describes the same.

是 APPCODA 的教程,描述了相同的内容。

and

Hereis the tutorial provided by Apple OBJ-C version.

是Apple OBJ-C版本提供的教程。

回答by Himanshu padia

Just posting this answer to help other user for this.

只是发布这个答案来帮助其他用户。

To open the specific document files of (.pdf, .doc, .docx)using UIDocumentPickerViewControllerin Swift: documentTypes would be

要在 Swift 中使用(.pdf、.doc、.docx)打开特定的文档文件UIDocumentPickerViewController:documentTypes 将是

import import MobileCoreServices

进口 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)