diff --git a/Sources/Models/YouTubePlayer+Source.swift b/Sources/Models/YouTubePlayer+Source.swift index bbce7ed..be054d4 100644 --- a/Sources/Models/YouTubePlayer+Source.swift +++ b/Sources/Models/YouTubePlayer+Source.swift @@ -85,29 +85,39 @@ public extension YouTubePlayer.Source { /// Creats `YouTubePlayer.Source` from a given URL string, if available /// - Parameter url: The URL string static func url( - _ url: String + _ urlString: String ) -> Self? { - // Initialize URLComonents from URL string - let urlComponents = URLComponents(string: url) - // Initialize URL from string - let url = URL(string: url) + // Initialize URL from string and call URL-based convenience method + guard let url = URL(string: urlString) else { + return nil + } + return Self.url(url) + } + + /// Creats `YouTubePlayer.Source` from a given URL, if available + /// - Parameter url: The URL + static func url( + _ url: URL + ) -> Self? { + // Initialize URLComonents from URL + let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) // Retrieve start seconds from "t" url parameter, if available let startSeconds = urlComponents?.queryItems?["t"].flatMap(Int.init) // Initialize PathComponents and drop first which is the leading "/" - let pathComponents = url?.pathComponents.dropFirst() + let pathComponents = url.pathComponents.dropFirst() // Check if URL host has YouTube share url host - if url?.host?.lowercased().hasSuffix("youtu.be") == true { + if url.host?.lowercased().hasSuffix("youtu.be") == true { // Check if a video id is available - if let videoId = pathComponents?.first { + if let videoId = pathComponents.first { // Return video source return .video( id: videoId, startSeconds: startSeconds ) } - } else if url?.host?.lowercased().contains("youtube") == true { + } else if url.host?.lowercased().contains("youtube") == true { // Otherwise switch on first path component - switch pathComponents?.first { + switch pathComponents.first { case "watch": // Check if a playlist identifier is available if let playlistId = urlComponents?.queryItems?["list"] { @@ -126,7 +136,7 @@ public extension YouTubePlayer.Source { } case "c", "user": // Check if a channel name is available - if let channelName = url?.pathComponents[safe: 2] { + if let channelName = url.pathComponents[safe: 2] { // Return channel source return .channel( name: channelName @@ -134,7 +144,7 @@ public extension YouTubePlayer.Source { } default: // Check if a video identifier is available - if let videoId = url?.pathComponents[safe: 2] { + if let videoId = url.pathComponents[safe: 2] { // Return video source return .video( id: videoId, @@ -146,7 +156,6 @@ public extension YouTubePlayer.Source { // Otherwise return nil return nil } - } // MARK: - Sequence+subscribt