点击UIDocumentInteractionController菜单的Quick Look图标无法打开文档如何解决?
UIDocumentInteractionController点击Quick Look无响应问题解决
问题根因
代码核心问题是 UIDocumentInteractionController实例没有被强引用持有。你将viewer声明为OpenDocument方法内的局部变量,方法执行完成后该变量没有其他强引用指向,会被系统垃圾回收机制自动销毁。当你点击菜单中的Quick Look选项时,对应的控制器实例已经不存在,因此没有任何响应,弹窗直接关闭。
修复代码
将UIDocumentInteractionController实例提升为类的全局成员,保证交互过程中不会被回收:
public class DataViewer { // 全局强引用持有控制器实例 private UIDocumentInteractionController _viewer; public event EventHandler DocumentOpened; public async Task OpenDocument(string filePath) { _viewer = UIDocumentInteractionController.FromUrl(new NSUrl(filePath, false)); // 原代码中事件处理无需async,无await操作时建议去掉避免警告 _viewer.WillBeginSendingToApplication += (sender, args) => { DocumentOpened?.Invoke(this, EventArgs.Empty); }; // 菜单关闭后释放引用,避免内存泄漏 _viewer.DidDismissOptionsMenu += (sender, args) => { _viewer = null; }; var controller = UIApplication.SharedApplication.KeyWindow.RootViewController; _viewer.PresentOptionsMenu(controller.View.Frame, controller.View, true); } }
其他排查项
- 确认传入的
filePath路径合法,对应文件真实存在,且应用拥有该路径的读取权限,访问沙盒外文件需要先申请对应的访问权限 - 确认Info.plist中已经添加了你需要预览的文档类型对应的UTI声明,否则系统无法识别对应格式的文件
内容的提问来源于stack exchange,提问作者szviktor94
相关产品推荐
相关产品推荐

