ios - 尝试使用 NSUrl(fileURLWithPath) 捕捉

标签 ios swift try-catch nsurl

我一直在尝试在下面的代码中实现 try 和 catch

if let s = songId {     
  let track: NSURL!
  track = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)
  .............
}

我想出了以下代码:

do {
  track = try NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)
}
catch let error as NSError {
  print("NSURL Error: \(error.localizedDescription)")
}

但我收到以下警告:

No calls to throwing functions occur within 'try' expression

'catch' block is unreachable because no errors are thrown in 'do' block

这对我来说很奇怪,因为这种结构通常有效。 只有使用 NSURL 时,这种结构才行得通。我不明白为什么会这样。也许这与它是可选的有关,但我不确定。 我不知道如何解决这个问题。我需要使用 try/catch 或类似的东西,但我不知道如何让它工作。

我在谷歌上看到了一些类似的问题,但没有给我答案。 所以我的问题是:如何使用 NSURL 实现 try/catch 构造或类似的东西?

提前致谢。

最佳答案

没有使用在定义中用 throws 关键字标记的方法。所以用 try-catch 包装你的代码真的没有多大意义。我建议考虑这一点:

let s = "song"
guard let trackURL = NSBundle.mainBundle().URLForResource(s, withExtension: "mp3") else {
  print("File not found in the app bundle: \(s).mp3")
  return false
}

有帮助吗?

关于ios - 尝试使用 NSUrl(fileURLWithPath) 捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570714/

相关文章:

javascript - 为什么此代码在 iPad Pro 上不起作用? (JS)

javascript - 我如何请求增加 iPad 上的 HTML5 localstorage 大小,就像 FT 网络应用程序一样?

ios - iOS 应用程序或 Playground 中的 Process 是否始终未解决?

vb.net - vb.net-主要方法或每种方法的错误处理

python:异常流程:捕获后继续向下捕获 block ?

ios - 在使用其他帐户发布之前使用 testflight 测试应用程序

cocoa-touch - 横向导航图像太短

ios - 无法访问 Firebase 子项

ios - Swift Mapkit 示例项目

java - 如何在发生InputMismatchException后重试输入?