0

My MPMediaplayer is working pretty well for Music, but when I start working with Podcasts things are different.

I'm trying to get two things: 1) The name the Podcast Title ("This American Life") 2) The Episode Title ("My Holiday")

This line of code works fine to get the Podcast Title:

let podTitle:String = (myMP.nowPlayingItem?.podcastTitle)!

However this line should get the Episode Title:

let episode:String = myMP.nowPlayingItem?.value(forProperty: "MPMediaItemPropertyTitle") as! String

but causes a crash with this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

How can I get the Episode Title for a given Podcast?

wayneh
  • 4,393
  • 9
  • 35
  • 70

1 Answers1

0

MPMediaItemPropertyTitle is not the string property key; it is the name of a constant whose value is the property key. So, where you have

let episode:String = 
  myMP.nowPlayingItem?.value(forProperty: "MPMediaItemPropertyTitle") as! String

...remove the quotation marks:

let episode:String = 
  myMP.nowPlayingItem?.value(forProperty: MPMediaItemPropertyTitle) as! String

I think what you are doing is still very foolish (you are asking to crash), but at least this way you stand a chance of success. What I do is actually more like this:

let temp = myMP.nowPlayingItem?.value(forProperty: MPMediaItemPropertyTitle)
let episode = temp as? String ?? ""

That way you always end up with a string, which may be empty if there's a problem, and you won't crash.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • It was the quotes that really got me - I'm pretty sure you need them in ObjC so I thought I also had to use them in Swift. Thanks! – wayneh Feb 19 '17 at 15:57
  • You don't "need them in ObjC". This is about the MediaPlayer framework, not what language you use. – matt Feb 19 '17 at 16:08