尝试和使用NSUrl(fileURLWithPath)

时间:2016-06-01 13:51:33

标签: 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)")
}

但我收到以下警告:

  

在尝试'尝试'表达

  

'捕捉'阻止无法访问,因为没有错误在' do'块

这对我来说很奇怪,因为这种结构通常有效。 只有NSURL这种结构不起作用。我无法弄清楚为什么会这样。也许它与它是可选的有关,但我不确定。 我无法弄清楚如何解决这个问题。我需要使用try / catch或类似的东西,但我无法弄清楚如何使其工作。

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

提前致谢。

2 个答案:

答案 0 :(得分:4)

在定义中没有使用标有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
}

有帮助吗?

答案 1 :(得分:2)

初始化程序不会失败并且不会抛出或失败,因此不需要try / catch块。声明是:

public init(fileURLWithPath path: String)

如果它可以抛出错误,则声明为:

public init(fileURLWithPath path: String) throws

或者如果它可能失败而不抛出错误,它将被声明为:

public init?(fileURLWithPath path: String)

如果您确定该套装将始终包含您正在寻找的曲目,那么您可以使用

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