2014-10-06 60 views
1

我想要“打开”菜单让我的应用程序打开一个文件,另一个用户可以选择。 这是我的代码,但我不能让它工作Swift:打开“在菜单中”选项

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_INSTRUCTION错误。 熟悉的代码为我工作Objective-C

回答

0

filename .pbz由于某种原因可能不存在于您的主包中。用你当前的代码,这将是一个致命的错误,并导致你的应用程序崩溃。

通过将url声明为NSURL!,您隐式地在您的第一行上展开url。通过在您致电URLForResource的电话上附加!,您可以在第二行上强制解开NSURL。如果filename .pbz未在您的主包中找到,那么您的应用程序将在第二行中崩溃,或者如果您在nil的某个位置尝试使用url

,才应使用武力展开,如果你是绝对确保变量将永远nil,并且只使用隐式展开,如果你是绝对肯定的变量不会nil当您使用它。

你应该做的是在你尝试使用它之前检查以确保你从URLForResource得到的url不是nil。您可以使用Optional Binding做到这一点很容易和安全地

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

你说得对:d也感谢为解决方案 – FrCr 2014-10-07 06:28:47

相关问题