-
-
Save xarbit/8f584818d423929753251b9e8ee6e0e7 to your computer and use it in GitHub Desktop.
Swift M3U Parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MediaItem { | |
var duration: Int? | |
var title: String? | |
var urlString: String? | |
static func parseM3U(contentsOfFile: String) -> [MediaItem]? { | |
var mediaItems = [MediaItem]() | |
contentsOfFile.enumerateLines({ line, stop in | |
if line.hasPrefix("#EXTINF:") { | |
let infoLine = line.stringByReplacingOccurrencesOfString("#EXTINF:", withString: "") | |
let infos = Array(infoLine.componentsSeparatedByString(",")) | |
if let durationString = infos.first, duration = Int(durationString) { | |
let mediaItem = MediaItem(duration: duration, title: infos.last, urlString: nil) | |
mediaItems.append(mediaItem) | |
} | |
} else { | |
if mediaItems.count > 0 { | |
var item = mediaItems.last | |
item?.urlString = line | |
} | |
} | |
}) | |
return mediaItems | |
} | |
} | |
if let | |
path = NSBundle.mainBundle().pathForResource("playlist", ofType: "m3u"), | |
contentsOfFile = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) { | |
MediaItem.parseM3U(contentsOfFile) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment