Sto cercando di capire come utilizzare la nuova API di YouTube (Versione 3) nella mia app per iOS ma non so come farlo. Ho fatto molte ricerche al riguardo ma quello che ho trovato sono tutti esempi e codici per le API meno recenti, quindi non sono validi. Fino ad ora ho capito che per usare la nuova API devi creare un progetto nella Google Developer Console (e l'ho fatto) ... ma poi ti mandano a una pagina con del codice ma non lo faccio davvero capire come usarlo link to google api page Quello che devo sapere è come recuperare alcune informazioni da un dato URL di un video di YouTube, le informazioni di cui ho bisogno sono il numero totale di "mi piace" e il numero totale di "visualizzazioni" ... con l'API 2 è stato molto semplice per farlo ... ma ora non so davvero da dove cominciare ... C'è qualcuno che per favore può spiegare come ottenerlo con forse alcuni esempi e qualche codice? Sono abbastanza sicuro che molte persone ne trarranno beneficio.Come utilizzare l'API di YouTube V3?
risposta
Non è necessario utilizzare il client iOS fornito da Google per effettuare questo tipo di richiesta.
Passare alla API Console e generare una nuova chiave di accesso semplice API per l'applicazione iOS. Assicurati di inserire l'identificativo del bundle dell'app nella finestra fornita. In alternativa, è possibile creare una chiave API server per testare le richieste di base e arricciare dalla riga di comando.
Trova l'endpoint pertinente per le tue esigenze. Per trovare informazioni su un video, ti consigliamo di utilizzare il metodo Videos.list.
In primo luogo, impostare l'URL. Userò questo URL come esempio: https://www.youtube.com/watch?v=AKiiekaEHhI
Stai per specificare un valore per il parametro part
. Dalla tua domanda, sembra che tu voglia passare i valori snippet
, contentDetails
e statistics
(sebbene per i Mi piace e le viste, in realtà hai solo bisogno del valore statistics
).
Quindi passare il id
del video (in questo caso AKiiekaEHhI
, è possibile aggiungere fino a 50 ID separati da virgola) e la chiave API. L'URL dovrebbe essere simile a questo:
https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}
Si può anche fare questo nel API Explorer.
Swift implementazione:
// Set up your URL
let youtubeApi = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}"
let url = NSURL(string: youtubeApi)
// Create your request
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
do {
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject] {
print("Response from YouTube: \(jsonResult)")
}
}
catch {
print("json error: \(error)")
}
})
// Start the request
task.resume()
implementazione Objective-C:
(. Questo post è stato modificato per supportare NSURLSession
Per un'implementazione che utilizza NSURLConnection
, controllare la cronologia di modifica)
// Set up your URL
NSString *youtubeApi = @"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY}";
NSURL *url = [[NSURL alloc] initWithString:youtubeApi];
// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
// Callback, parse the data and check for errors
if (data && !connectionError) {
NSError *jsonError;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (!jsonError) {
NSLog(@"Response from YouTube: %@", jsonResult);
}
}
}] resume];
Il tuo registro sarà simile a questo:
Response from YouTube: {
etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/AAjIATmVK_8ySsAWwEuNfdZdjW4\"";
items = (
{
contentDetails = {
caption = false;
definition = hd;
dimension = 2d;
duration = PT17M30S;
licensedContent = 1;
};
etag = "\"NO6QTeg0-3ShswIeqLchQ_mzWJs/8v8ee5uPZQa1-ucVdjBdAVXzcZk\"";
id = AKiiekaEHhI;
kind = "youtube#video";
snippet = {
categoryId = 20;
channelId = UCkvdZX3SVgfDW8ghtP1L2Ug;
channelTitle = "Swordless Link";
description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
liveBroadcastContent = none;
localized = {
description = "Follow me on Twitter! http://twitter.com/swordlesslink\n\nFollow me on TwitchTV for live video game streaming! http://twitch.tv/swordlesslink";
title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
};
publishedAt = "2015-05-04T10:01:43.000Z";
thumbnails = {
default = {
height = 90;
url = "https://i.ytimg.com/vi/AKiiekaEHhI/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i.ytimg.com/vi/AKiiekaEHhI/hqdefault.jpg";
width = 480;
};
medium = {
height = 180;
url = "https://i.ytimg.com/vi/AKiiekaEHhI/mqdefault.jpg";
width = 320;
};
standard = {
height = 480;
url = "https://i.ytimg.com/vi/AKiiekaEHhI/sddefault.jpg";
width = 640;
};
};
title = "The Legend of Zelda: Majora's Mask With Glitches - Part 17: Going Against the Flow";
};
statistics = {
commentCount = 54;
dislikeCount = 3;
favoriteCount = 0;
likeCount = 265;
viewCount = 6356;
};
}
);
kind = "youtube#videoListResponse";
pageInfo = {
resultsPerPage = 1;
totalResults = 1;
};
} with error: nil
L'oggetto per la chiave items
sarà un array di informazioni per ciascun ID video passato alla richiesta.
Scavando in questa risposta, sarete in grado di ottenere le informazioni necessarie.Per esempio:
if let items = jsonResult["items"] as? [AnyObject]? {
println(items?[0]["statistics"])
}
vi darà un dizionario delle statistiche del video (in cui è possibile ottenere il numero di simpatie e il numero di visualizzazioni).
{
commentCount = 54;
dislikeCount = 3;
favoriteCount = 0;
likeCount = 265;
viewCount = 6356;
}
Questo stesso approccio può essere utilizzato con eventi dal vivo.
// 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()
}
sua piuttosto semplice da usare. Si può usare da JavaScript, è presente un modulo semplice in npmjs: https://www.npmjs.com/package/youtube-api-es6
E, il suo riferimento che ho trovato sul suo Web: https://www.gyanblog.com/gyan/44-youtube-api-nodejs-usage-example
Hey! Grazie per la tua risposta, programma con Objective c e Xcode, domani cercherò di utilizzare le tue informazioni nel mio progetto e ti faccio sapere ... Grazie per il tuo aiuto – Blue
@Blue Dovresti davvero cambiare i tag sulla tua domanda allora. iOS! = Objective-C, e Xcode utilizza sia Objective-C che Swift. Tuttavia, ho aggiunto un'implementazione Objective-C e richiesto una modifica alla tua domanda per includere il tag Objective-C. – JAL
@Blue eventuali aggiornamenti o domande? Per favore fatemi sapere se avete bisogno di aiuto con qualcos'altro. – JAL