Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift:开放式“;“在菜单中”;选项_Ios_Menu_Swift - Fatal编程技术网

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 */
}