3 // Protocol to obtain the track from iTunes
4 @objc protocol iTunesTrack {
5 @objc optional var name: String {get}
6 @objc optional var artist: String {get}
9 // Protocol to interact with iTunes
10 @objc protocol iTunesApplication {
11 @objc optional var currentTrack: iTunesTrack? {get}
12 @objc optional var currentStreamTitle: String? {get}
15 extension SBApplication : iTunesApplication {}
17 // Source that reads track artist and name from current itunes track
18 class ItunesSource: Source {
20 // Calls the spotify API and returns the current track
21 var currentTrack: Track? {
23 if let iTunes: iTunesApplication = SBApplication(bundleIdentifier: "com.apple.iTunes") {
25 // Attempt to fetch the title from a stream
26 if let currentStreamTitle = iTunes.currentStreamTitle {
27 if let track = currentStreamTitle {
29 let trackComponents = track.characters.split(separator: "-").map(String.init)
31 if trackComponents.count == 2 {
32 let artist = trackComponents[0].trimmingCharacters(in: .whitespaces)
33 let name = trackComponents[1].trimmingCharacters(in: .whitespaces)
35 return Track(withName: name, andArtist: artist)
41 // Attempt to fetch the title from a song
42 if let currentTrack = iTunes.currentTrack {
43 if let track = currentTrack {
44 if let name = track.name {
45 if let artist = track.artist {
47 // track properties are empty strings if itunes is closed
48 if (!(name != "" && artist != "")) {
51 return Track(withName: name, andArtist: artist)