如何在iOS移动设备上使用Swift 3.0编写按钮操作以打开文档文件(例如.pdf、.doc、.docx)?

20

我需要打开UIDocumentPickerViewController,并且应该允许用户选择所有类型的文件,例如(.pdf、.doc)文件。我使用了UIDocumentPickerViewController方法。

我的代码:

UIDocumentPickerDelegate, UIDocumentMenuDelegate在我的类声明中。

//上传文件

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)        

}

在这段代码中,应用程序将崩溃。原因是Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: 'You cannot initialize a UIDocumentPickerViewController except by the initWithDocumentTypes:inMode: and initWithURL:inMode: initializers.

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

4个回答

22

Swift 3*,4*

打开文档并选择任何文档时,您将使用UIDocumentPickerViewController,然后如果用户设备上连接了Google Drive,则会显示iCloud、文件和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)

               }
   }

注意:如果您希望选择所有文件,则必须使用以下代码:

  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) 

在您的操作方法中。


@mouni关掉iCloud的东西,方法如下,通过此图片进行操作:https://imgur.com/a/ntubG - Abhishek Mitra
我也关闭了iCloud,但是我仍然遇到了一个错误:“- [UIDocumentPickerViewController _commonInitWithCompletion:]”中的断言失败,“/ BuildRoot / Library / Caches / com.apple.xbs / Sources / UIKit / UIKit-3600 .9.1 / UIDocumentPickerViewController.m:91”,应用程序因未捕获的异常“NSInternalInconsistencyException”而终止,原因是“初始化文档选择器的应用程序缺少iCloud授权。是否设置了com.apple.developer.icloud-container-identifiers?” - mouni
@mouni,你是什么时候发现这个崩溃的?是在调用actionSheet代理方法的时候吗?我无法通过这种方式编译你的代码。 - Abhishek Mitra
func OpenFile(){ } 函数。takefile() 不需要了。我隐藏了这个函数。 - mouni
根据您的代码,您正在从“actionSheet”调用“OpenFile()”,当调用“OpenFile()”时,它会崩溃。我没有发现任何异常之处,除非您尝试使用“DispatchQueue.main.async {print(“Async1”)}”。另外,请问编译器是否进入了“didPickDocumentAt”这个委托方法? - Abhishek Mitra
显示剩余13条评论

17

使用UIDocumentPickerViewController在Swift中打开特定文件类型的文档(如.pdf,.doc,.docx):

documentTypes 应为:

import MobileCoreServices

["com.microsoft.word.doc","org.openxmlformats.wordprocessingml.document", kUTTypePDF as String]

例子:

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)

是的,它是用于 xls 文件的。 - Himanshu padia
我们需要使用什么类型的文件来处理“Excel”文件。 - undefined

15
实际上,您也可以使用专门为此目的设计的QuickLook Framework,而不是WebView。您只需传递文件位置并符合协议即可。它将呈现包含文档的视图控制器。
它支持以下文件:
- iWork文档(Pages,Numbers和Keynote) - Microsoft Office文档(只要它们是使用Office 97或任何更新版本创建的) - PDF文件 - 图像 - 文本文件 - Rich-Text格式文档 - 逗号分隔值文件(csv) 这里是由APPCODA提供的描述相同内容的教程。
以及 这里是由苹果OBJ-C版本提供的教程。

很酷!很高兴能帮到你! - Umar Farooque
1
这应该是被采纳的答案。使用QuickLook Framework 渲染文档比使用 WebView 更好。 - Velociround

1

UIDocumentPickerViewController.init(documentTypes:in:)kUTType___ 在 iOS 14 和 15 中已被弃用。以下是在新版本的 iOS 上实现相同功能的方法:

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

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

我们需要使用什么类型的文件来处理"Excel"文件? - undefined
@Jain_Taresh 我相信是 UTType.init(filenameExtension: "xls")UTType.init(filenameExtension: "xlsx") - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接