I'm trying to figure out how to use the new YouTube API (Version 3) in my iOS app but I don't know how to do it. I did many research about it but what I found is all examples and codes for older API so they are not valid. Til now I did understand that for using the new API you have to create a Project in Google Developer Console (and I did it)... but then they send you to a page with some code on it but I really don't understand how to use it. link to google api page What I need to know is how to retrieve some informations from a given URL of a YouTube video, the informations I need are total number of "likes" and total number of "views"... with API 2 it was very simple to do it... but now I really don't know where to begin... Is there someone that please can explain how to achieve this with maybe some examples and some code? I'm pretty sure that a lot of people will benefit from this.
// Swift 3
func search() {
let videoType = "video you want to search"
// can use any text
var dataArray = [[String: AnyObject]]()
// store videoid , thumbnial , Title , Description
var apiKey = "_________________"
// create api key from google developer console for youtube
var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(videoType)&type=video&videoSyndicated=true&chart=mostPopular&maxResults=10&safeSearch=strict&order=relevance&order=viewCount&type=video&relevanceLanguage=en®ionCode=GB&key=\(apiKey)"
urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
let targetURL = URL(string: urlString)
let config = URLSessionConfiguration.default // Session Configuration
let session = URLSession(configuration: config)
let task = session.dataTask(with: targetURL!) {
data, response, error in
if error != nil {
print(error!.localizedDescription)
var alert = UIAlertView(title: "alert", message: "No data.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
else {
do {
typealias JSONObject = [String:AnyObject]
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! JSONObject
let items = json["items"] as! Array<JSONObject>
for i in 0 ..< items.count {
let snippetDictionary = items[i]["snippet"] as! JSONObject
print(snippetDictionary)
// Initialize a new dictionary and store the data of interest.
var youVideoDict = JSONObject()
youVideoDict["title"] = snippetDictionary["title"]
youVideoDict["channelTitle"] = snippetDictionary["channelTitle"]
youVideoDict["thumbnail"] = ((snippetDictionary["thumbnails"] as! JSONObject)["high"] as! JSONObject)["url"]
youVideoDict["videoID"] = (items[i]["id"] as! JSONObject)["videoId"]
dataArray.append(youVideoDict)
print(dataArray)
// video like can get by videoID.
}
}
catch {
print("json error: \(error)")
}
}
}
task.resume()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With