我创建了一个名为PreviewFile
的自定义类:
class PreviewFile: UIViewController , UIDocumentInteractionControllerDelegate {
var documentInteractionController = UIDocumentInteractionController()
func previewFile(name:String) {
let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!,isDirectory: true )
let urlToMyPath = documentsURL.appendingPathComponent(name)!
documentInteractionController = UIDocumentInteractionController(url: urlToMyPath)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)
}
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
然后我在ViewController上调用previewFile
方法:
var preview = PreviewFile()
preview.previewFile(name:"guide.pdf")
但是编译器给了我这个错误:
警告:尝试出现 谁的观点不在窗口 层次!
答案 0 :(得分:1)
class PreviewFile: UIViewController , UIDocumentInteractionControllerDelegate {
private var controller: UIViewController!
func previewFile(name:String, in controller: UIViewController) {
self.controller = controller
let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!,isDirectory: true )
let urlToMyPath = documentsURL.appendingPathComponent(name)!
let documentInteractionController = UIDocumentInteractionController(url: urlToMyPath)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)
}
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.controller
}
}
然后你就可以从UIViewController中调用它了:
var preview = PreviewFile()
preview.previewFile(name:"guide.pdf", in self)
你有这个问题,因为你试图从PreviewFile控制器显示documentDirectory,屏幕上没有显示的内容
更新#1 更好的解决方案
class PreviewFile: NSObject, UIDocumentInteractionControllerDelegate {
private var controller: UIViewController!
init(controller: UIViewController) {
super.init()
self.controller = controller
}
func previewFile(name:String) {
let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!,isDirectory: true )
let urlToMyPath = documentsURL.appendingPathComponent(name)!
let documentInteractionController = UIDocumentInteractionController(url: urlToMyPath)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)
}
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.controller
}
}
这样称呼:
var preview = PreviewFile(controller: self)
preview.previewFile(name:"guide.pdf")