为什么我在Swift文件中展开nil?

时间:2015-03-02 22:34:20

标签: json swift audio avfoundation itunes

我有一个应用程序(我之前关于展开nil的帖子中的同一个。我现在非常讨厌nil。)搜索iTunes商店并以JSON格式返回数据。我有它工作,它得到歌曲名称,艺术家名称,一切!我创建了一个@IBAction按钮来播放歌曲的预览。 JSON有一个属性,是歌曲预览的网址。当我单击按钮时,它会执行以下操作:

        let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(url, ofType: "m4a")!)
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()

url就是:http://a1993.phobos.apple.com/us/r1000/101/Music/b7/b3/e0/mzm.ooahqslp.aac.p.m4a。我知道我播放音频文件的设置有效;我有另一个我正在构建的应用程序使用完全相同的设置。为什么告诉我我在这里展开nilhttp://a1993.phobos.apple.com/us/r1000/101/Music/b7/b3/e0/mzm.ooahqslp.aac.p.m4a?网址有效,文件播放。

2 个答案:

答案 0 :(得分:0)

检查这行代码。

let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(url, ofType: "m4a")!)

fileUrlWithPath要求提供本地路径,即您设备上的路径。

NSBundle.mainBundle().pathForResource(url.....

此方法返回您发送给它的资源的本地路径。你发送的是一个网址,除非你明确地把它放在那里,否则它不在mainBundle中。所以它返回的路径是nil,因为没有本地路径满足你传递给它的参数。

答案 1 :(得分:0)

如果您有本地资源,则应使用名为URLForResource

的方法

这条线毫无意义。你应该总是喜欢使用url并在需要时从中提取路径。

替换此行:

let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fileName", ofType: "m4a")!)  // this would crash if not found (nil)

使用此代码块

if let alertSoundUrl =  NSBundle.mainBundle().URLForResource("fileName", withExtension: "m4a") {
    println(true)
} else {
    println(false)
}

如果是网络链接,则需要使用NSURL(字符串:)。 fileUrlWithPath它仅适用于本地资源。

if let checkedUrl = NSURL(string: "http://a1993.phobos.apple.com/us/r1000/101/Music/b7/b3/e0/mzm.ooahqslp.aac.p.m4‌​") {
    println(true)
} else {
    println(false)
}