ios - UIDocumentPickerViewController - 未调用委托方法
问题描述
我正在使用 UIDocumentPickerViewController 从文件中选择文档并将其上传到服务器。我能够成功访问文件,但是单击文件后,不会调用委托方法。
我使用以下代码来调用文档选择器:
class Uploads: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func uploadDocument(_ sender: Any) {
let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF), String(kUTTypePlainText)], in: .import)
documentPicker.delegate = self
if #available(iOS 11.0, *) {
documentPicker.allowsMultipleSelection = false
} else {
}
present(documentPicker, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension Uploads: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print(urls.first)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Cancelled")
}
}
我注意到调用委托方法时收到以下警告:
实例方法 'documentPicker( :didPickDocumentsAt:)' 几乎匹配协议 'UIDocumentPickerDelegate' 的可选要求 'documentPicker( :didPickDocumentsAt:)'
将 'documentPicker(_:didPickDocumentsAt:)' 设为私有以消除此警告
我相信由于这个警告而没有调用委托方法,尽管我不知道为什么我会收到这个警告。
解决方案
分享代码示例希望它会有所帮助:
class ViewController : UIViewController,UIDocumentPickerDelegate{
var documentBrowser: UIDocumentPickerViewController = {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let browser = UIDocumentPickerViewController(documentTypes: [documentsPath], in: .open)
browser.allowsMultipleSelection = true
return browser
}()
override func viewDidLoad() {
super.viewDidLoad()
self.addChild(documentBrowser)
documentBrowser.view.frame = self.view.bounds
view.addSubview(documentBrowser.view)
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]){
print(urls)
}
}
推荐阅读
- reactjs - React-router-dom 导航链接未呈现
- css - 无法在 HTML/CSS 中添加本地图像作为背景图像
- node.js - 当行分隔符为换行符且 csv 数据中包含换行符时,如何使用 fs readfile 读取 csv?
- java - INSERT IGNORE 在 mysql 模式下使用 h2 引发主键冲突
- c# - Fluent Migration:如何在删除/更新语句中添加和/或子句
- javascript - 如何修复输入字段不通过多次更改更新 Firebase
- text - 如何仅删除 TextField 中没有文本的行?
- python - Pandas - 如何通过各种条件对多列进行“分组”?
- c# - 将年份值分配给 sbyte
- oracle - Oracle DB 12C 的 SQL Developer 连接错误