如何访问云端硬盘以在swift中将文件导入我的应用程序?

时间:2016-07-26 05:34:39

标签: ios swift dropbox icloud

我想通过按钮点击获取云服务(如iCloud,google drive和dropbox)的文档(如下面的WhatsApp截图所示),有没有人知道如何在swift中执行此操作?提前致谢

enter image description here

2 个答案:

答案 0 :(得分:15)

从您的项目的能力。首先启用iCloud服务和密钥共享,在您的类中导入MobileCoreServices,最后在UIViewController中扩展以下三个类:

UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate

实施以下功能:

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
              let myURL = url as URL
              print("import result : /(myURL)")
    }


public 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)
    }

如何调用所有这些?将以下位代码添加到您的点击功能..

func clickFunction(){

let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
            importMenu.delegate = self
            importMenu.modalPresentationStyle = .formSheet       
            self.present(importMenu, animated: true, completion: nil)
}

单击您的按钮。将弹出以下菜单..

MenuPicker

在DropBox的情况下。点击任何项目。您将被重定向回您的应用程序,并且该URL将记录在您的终端中。

enter image description here

根据需要操作documentTypes。在我的应用程序中,用户只允许使用Pdf。所以,适合自己。

kUTTypePDF

此外,如果您想要自定义自己的菜单栏。添加以下代码并在处理程序

中自定义您自己的函数
        importMenu.addOption(withTitle: "Create New Document", image: nil, order: .first, handler: { print("New Doc Requested") })

enter image description here

享受它。

答案 1 :(得分:2)

首先启用iCloud文档功能,请参阅Apple文档here

您必须使用UIDocumentMenuViewController

let importMenu = UIDocumentMenuViewController(documentTypes: doctypes, inMode: .Import)
importMenu.delegate = self
importMenu.popoverPresentationController?.barButtonItem = self.addButon;
self.presentViewController(importMenu, animated: true, completion: nil)