Ios Swift:开放式“;“在菜单中”;选项
我想使用“打开”菜单,让我的应用程序打开一个文件,用户可以选择另一个文件。 这是我的代码,但我不能让它工作Ios Swift:开放式“;“在菜单中”;选项,ios,menu,swift,Ios,Menu,Swift,我想使用“打开”菜单,让我的应用程序打开一个文件,用户可以选择另一个文件。 这是我的代码,但我不能让它工作 var url: NSURL! = NSBundle.mainBundle().URLForResource(filename, withExtension: "pbz") self.controller = UIDocumentInteractionController(URL: NSBundle.mainBundle().URLForResource(filen
var url: NSURL! = NSBundle.mainBundle().URLForResource(filename, withExtension: "pbz")
self.controller = UIDocumentInteractionController(URL: NSBundle.mainBundle().URLForResource(filename, withExtension: "pbz")!)
let v = sender as UIView
let ok = self.controller.presentOpenInMenuFromRect(v.bounds, inView: self.view, animated: true)
你知道吗?它可以编译,但在运行时,在第二条指令中给我一个EXC_BAD_指令错误。
类似的代码对我来说适用于Objective-C
文件名
。出于某种原因,pbz可能不存在于您的主捆绑包中。对于当前代码,这将是一个致命错误,并导致应用程序崩溃
通过将url
声明为NSURL,您在第一行隐式展开url
代码>。通过附加,您正在第二行强制展开您的NSURL
调用URLForResource
。如果在主捆绑包中找不到filename
.pbz,则应用程序将在第二行崩溃,或者如果您试图在nil
的某个位置使用url
只有绝对确定变量永远不会为nil
时,才应使用强制展开;只有绝对确定变量使用时不会为nil
时,才应使用隐式展开。
相反,您应该做的是检查确保从URLForResource
返回的url
在您尝试使用它之前不是nil
。您可以使用来轻松安全地执行此操作:
if let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "pbz") {
self.controller = UIDocumentInteractionController(URL: url)
let v = sender as UIView
let ok = self.controller.presentOpenInMenuFromRect(v.bounds, inView: self.view, animated: true)
} else {
/* resource doesn't exist */
}