YouTubeKit is a powerful Swift package to make requests to the YouTube API without having any API key.
DocC is available here.
Make sure that your implementation and usage of YouTubeKit are legal and make sure to tell the potential users of your app the eventual risks they encounter when they use your implementation.
- Install the package to your Xcode project:
- In the top menu go to File->Add Packages...
- Enter the link of this repository: https://github.com/b5i/YouTubeKit (you may have to connect Xcode to your github account).
- Click on
Add Package
. - Use it in your project by importing it:
import YouTubeKit
.
Please note that this is adapted from another iOS app and so is in constant developpement.
Here is a list of the default requests supported by YouTubeKit, all the informations you can get are:
-
HomeScreenResponse -> get videos from the main page of YouTube, its Continuation is also available.
-
SearchResponse -> get results for a text query, its Continuation is also available.
-
SearchResponse.Restricted -> get Creative Commons copyrighted results for a text query.
-
VideoInfosResponse -> get the infos of a video by ID. Warning: Setting the
useCookies
parameter to true when using this request will not have any effect (except if you launch the request using theYouTubeModel
) because it wouldn't work with the YouTube API. -
VideoInfosWithDownloadFormatsResponse -> get the infos of a video by ID and the DownloadFormats, consumes more bandwidth than VideoInfosResponse but has an array of DownloadFormat.
-
MoreVideoInfosResponse to get various informations about a video (see documentation).
-
TrendingVideosResponse to the trending tabs.
-
AutoCompletionResponse -> get autoCompletion suggestions from a text query.
-
ChannelInfosResponse -> get infos of a YouTube channel by its id.
-
PlaylistInfosResponse -> get a playlist's informations and the videos it contains. Its Continuation is also available.
- AccountInfosResponse to get the informations about a YouTube account (using the cookies).
- AccountLibraryResponse to get the library of an account.
- AccountPlaylistsResponse to get the playlists of an account.
- AccountSubscriptionsFeedResponse to get the feed of the account's subscriptions.
- AccountSubscriptionsResponse to get the list of channel that the account is subscribed to.
- HistoryResponse and RemoveVideoFromHistroryResponse to get the history of an account and remove some videos of it.
- SubscribeChannelResponse and UnsubscribeChannelResponse.
- AllPossibleHostPlaylistsResponse to get all the playlists a video could be added to and if the video is already present inside.
- AddVideoToPlaylistResponse, CreatePlaylistResponse, DeletePlaylistResponse, MoveVideoInPlaylistResponse, RemoveVideoByIdFromPlaylistResponse and RemoveVideoFromPlaylistResponse to manage an account's playlists.
- LikeVideoResponse, DislikeVideoResponse and RemoveLikeFromVideoResponse.
- CreateCommentResponse to create a comment on a video.
- EditCommentResponse to edit a comment on a video.
- DeleteCommentResponse to delete a comment from a video.
- ReplyCommentResponse to create a reply to a comment.
- EditReplyCommandResponse to edit a reply to a comment on a video.
- DislikeCommentResponse to dislike a comment on a video.
- LikeCommentResponse to like a comment on a video.
- RemoveDislikeCommentResponse to remove a dislike from a comment.
- RemoveLikeCommentResponse to remove a like from a comment.
- CommentTranslationResponse to get the translation to a comment (does not require an account).
Every possible request within YouTubeKit conforms to the protocol YouTubeResponse, it contains a few useful methods:
static var headersType
is a static variable indicating the type of headers used to make the request, its documentation indicates which parameter to provide in order to make the request work.static var parametersValidationList
is a static variable indicating if further processing and validation should be done on the parameters of the request. It can be validating that a videoId has the right format or simply that a parameter is provided.static func validateRequest(data: inout RequestData) throws
is the method that will be called before sending the request over the internet. It will forward the errors given by the validators fromparametersValidationList
if there's some.static func decodeData(data: Data) throws -> Self
is a static method used to decode some Data and give back in instance of theYouTubeResponse
. Except for some special cases (if the raw data can't directly be converted into JSON for instance), you won't need to override the default implementation of this method.static func decodeJSON(json: JSON) throws -> Self
is a static method used to decode some JSON and give back in instance of theYouTubeResponse
, if the JSON does not represent a proper response it will return an empty response (only nils and empty arrays). Can throw aResponseExtractionError
if a critical extraction step fails.static func checkForErrors(json: JSON) throws
is a static method that should be called before callingdecodeJSON(json: JSON)
to avoid trying to decode some JSON that represents an error. Except for some special cases (errors returned for this request are in a non-standart format), you won't need to override the default implementation.static func sendNonThrowingRequest()
andstatic func sendThrowingRequest()
are static methods that allows you to make requests, by using async await system or closures. Its usage will be precised in the following tutorial.
With YouTubeKit you can make a large variety of requests to the YouTube API, new request types are added often and you can even create your own in Custom requests/responses.
- Make sure you have an instance of
YouTubeModel
, if not you can create one with
let YTM = YouTubeModel()
-
Define the request's data parameters, to get the demanded headers you can look at the definition of your
YouTubeResponse.headersType
it should describe which data to send. An example with aSearchResponse
:a. Right click on the type of request and press
Jump to definition
, theSearchResponse.headersType
isHeaderTypes.search
.b. Its definition is
/// Get search results. /// - Parameter query: Search query case search
it means that you will have to provide a query for the request to work and give a relevant result.
c. You will define the data parameters like this:
let textQuery: String = "my super query" let dataParameters: [HeadersList.AddQueryInfo.ContentTypes : String] = [ .query: textQuery ]
-
Execute the request with (e.g. a
SearchResponse
request)
SearchResponse.sendNonThrowingRequest(youtubeModel: YTM, data: dataParameters, result: { result, error in
switch result {
case .success(let response):
/// Process here the result.
print(response)
case .failure(let error):
/// If there is no result you should obtain an error explaining why there is none.
print(error)
}
})
you can also send the request without explicitly declaring dataParameters
like this:
SearchResponse.sendNonThrowingRequest(youtubeModel: YTM, data: [.query: textQuery], result: { result in
switch result {
case .success(let response):
/// Process here the result.
print(response)
case .failure(let error):
/// If there is no result you should obtain an error explaining why there is none.
print(error)
}
})
and even use the async/throws API like this:
let result = try await SearchResponse.sendThrowingRequest(youtubeModel: YTM, data: [.query: textQuery])
switch result {
case .success(let response):
/// Process here the result.
print(response)
case .failure(let error):
/// If there is no result you should obtain an error explaining why there is none.
print(error)
}
YouTubeKit allows you to add an account's cookies into the requests by following those steps:
- Define the cookies variable in your YouTubeModel:
let YTM = YouTubeModel()
YTM.cookies = "myCookies"
- If you want to always use cookies when making requests you can opt to set the
alwaysUseCookies
of theYouTubeModel
like so:
let YTM = YouTubeModel()
YTM.cookies = "myCookies"
YTM.alwaysUseCookies = true
- You can also choose to use cookies by request by specifying the
useCookies
parameter present in every request function.
YouTubeKit has a built-in way to actively debug requests/responses at runtime.
- For that, create your type of
RequestsLogger
and add it to thelogger
property of yourYouTubeModel
.
class Logger: RequestsLogger {
var loggedTypes: [any YouTubeResponse.Type]? = nil
var logs: [YouTubeKit.RequestLog] = []
var isLogging: Bool = false
var maximumCacheSize: Int? = nil
}
let logger = Logger()
YTM.logger = logger
- Enable logging by calling the
startLogging
method of your logger:
logger.startLogging()
- A full log of every request that has finished when
logger.isLogging
is true is stored inlogger.logs
by chronological order. Be aware that enabling logging can consume a lot of RAM as the logger stores a lot of raw informations. Therefore, make sure that you regularly clear thelogger.logs
usinglogger.clearLogs
, disable logging when it's not needed or set a reasonable cache limit usinglogger.setCacheSize()
.
A lot of structures and protocol have custom request calls (shortcuts to various YouTubeResponse
), here is a few examples:
1. `YouTubeVideo` (`YTVideo` conforms to it) has:
1. `fetchStreamingInfos` that can be used to retrieve the basic streaming data.
2. `fetchStreamingInfosWithDownloadFormats` that is the same as `fetchStreamingInfos` but it includes the download formats (all the different video/audio formats you can stream/download the video).
3. `fetchMoreInfos` that can be used to retrieve more infos about the video (recommended videos, description with chapters and links, and more!).
4. `likeVideo`, `dislikeVideo`, `removeLikeFromVideo`.
5. `fetchAllPossibleHostPlaylists`
2. `YouTubeChannel` (`YTChannel`and `YTLittleChannelInfos` are conform to it) has:
1. `fetchInfos` that can be used to retrieve various informations about the channel.
3. `ContinuableResponse` (`HomeScreenResponse`, `SearchResponse`, `PlaylistInfosResponse` are conform to it) has:
1. `mergeContinuation` to merge the continuations easily.
2. `fetchContinuation` to get those continuations.
4. `HistoryResponse` has `removeVideo` that can be used to remove a video from the history.
To create custom headers and so custom request/response function, you have to:
- Append the function that is used to generate the
HeadersList
inYouTubeModel.customHeadersFunctions
, e.g
let YTM = YouTubeModel()
let myCustomHeadersFunction: () -> HeadersList = {
HeadersList(
url: URL(string: "https://www.myrequesturl.com")!,
method: .POST,
headers: [
.init(name: "Accept", content: "*/*"),
.init(name: "Accept-Encoding", content: "gzip, deflate, br"),
.init(name: "Accept-Language", content: "\(YTM.selectedLocale);q=0.9"),
],
addQueryAfterParts: [
.init(index: 0, encode: true)
],
httpBody: [
"my query is: ",
" and it is really cool!"
]
)
}
YouTubeModel.shared.customHeadersFunctions["myHeadersID"] = myCustomHeadersFunction
- Create the response that is conform to the YouTubeResponse protocol, e.g
/*
We imagine that the JSON is of the form:
{
"name": "myName",
"surname": "mySurname"
}
*/
/// Struct representing a getNameAndSurname response.
public struct NameAndSurnameResponse: YouTubeResponse {
public static let headersType: HeaderTypes = .customHeaders("myHeadersID") //<- the myHeadersID has to be the same as the one you defined in step 1!
public static let parametersValidationList: ValidationList = [:] // we don't need any validators here as there's no parameters to provide.
/// String representing a name.
public var name: String = ""
/// String representing a surname.
public var surname: String = ""
public static func decodeJSON(json: JSON) -> NameAndSurnameResponse {
/// Initialize an empty response.
var nameAndSurnameResponse = NameAndSurnameResponse()
nameAndSurnameResponse.name = json["name"].stringValue
nameAndSurnameResponse.surname = json["surname"].stringValue
return nameAndSurnameResponse
}
}
- And to exectute it you just have to call
func sendRequest( youtubeModel: YouTubeModel, data: [HeadersList.AddQueryInfo.ContentTypes : String], result: @escaping (Result<ResponseType, Error>) -> () )
e.g,
/// We continue with our example:
NameAndSurnameResponse.sendNonThrowingRequest(youtubeModel: YTM, data: [:], result: { result in
switch result {
case .success(let response):
/// Process here the result.
print(response)
case .failure(let error):
/// If there is no result you should obtain an error explaining why there is none.
print(error)
}
})
Note: you would include in the request the parameters if needed like: query, browseId or anything like this to put in the body of the request to send.
This category lists solutions to problems you might encounter with YouTubeKit.
-
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found."
This issue can be resolved by enabling the
Outgoing Connections (Client)
in theSigning & Capabilities
category of your project's target in Xcode. -
The download speed is very low when downloading an audio-only
DownloadFormat
: this issue can be resolved by adding therange: bytes=0-(CONTENT_LENGHT_BYTES)
HTTP header to yourURLRequest
(e.g.request.addValue("bytes=0-\(myDownloadFormat.contentLength ?? "")", forHTTPHeaderField: "range")
).
- The result of a request is empty: this issue could be caused by the locale that could be in the wrong format. Make sure that your
YouTubeModel.selectedLocale
is likeen-US
.
Thanks to the SwiftyJSON library for facilitating the JSON extraction!
Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
``