2015-05-17 254 views
9

我想弄清楚如何在我的iOS應用程序中使用新的YouTube API(版本3),但我不知道該怎麼做。 我做了很多關於它的研究,但是我發現的是所有舊API的示例和代碼,因此它們無效。 直到現在我明白了,要使用新的API,您必須在Google開發者控制檯中創建一個項目(並且我這麼做了)......但是,然後他們會將您帶到一個包含一些代碼的頁面,但我實際上沒有了解如何使用它。 link to google api page 我需要知道的是如何從YouTube視頻的給定網址中檢索一些信息,我需要的信息是「喜歡」的總數和「視圖」的總數......對於API 2,它非常簡單做到這一點...但現在我真的不知道從哪裏開始... 有沒有人請解釋如何實現這一點,也許一些例子和一些代碼? 我很確定很多人都會從中受益。如何使用YouTube API V3?

回答

18

您不必使用Google提供的iOS客戶端來提出這些請求。

  1. 導航到API Console併爲您的iOS應用程序生成一個新的簡單API訪問鍵。請確保在提供的窗口中輸入您的應用程序的包標識符。或者,您可以創建一個服務器API密鑰,用於通過命令行進行基本請求測試和捲曲。

  2. 找到您需要的相關端點。要查找有關視頻的信息,您需要使用Videos.list方法。

首先,設置你的URL。我將以此URL爲例:https://www.youtube.com/watch?v=AKiiekaEHhI

您將要爲part參數指定一個值。從你的問題,它看起來像你會想在snippetcontentDetails,並statistics值傳遞(雖然喜歡和看法,你真的只需要statistics值)。

然後通過視頻的id(在這種情況下,AKiiekaEHhI,您最多可以添加50個以逗號分隔的ID)和您的API密鑰。您的網址應如下所示:

https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key={YOUR_API_KEY} 

您也可以在API Explorer中執行此操作。

迅速實施:

// 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() 

Objective-C的實現:

(該帖子已被編輯,以支持NSURLSession對於使用NSURLConnection的實施,檢查編輯歷史)

// 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]; 

你的日誌將是這個樣子:

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 

items鍵的對象將是你傳遞到請求中的每個視頻的ID信息的數組。

通過挖掘到這種反應,你就可以得到你所需要的信息。例如:

if let items = jsonResult["items"] as? [AnyObject]? { 
    println(items?[0]["statistics"]) 
} 

會給你一個視頻的統計字典(你可以得到喜歡的數量和視圖的數量)字典。

{ 
    commentCount = 54; 
    dislikeCount = 3; 
    favoriteCount = 0; 
    likeCount = 265; 
    viewCount = 6356; 
} 

這種方法可以用於現場活動。

+0

嘿!感謝您的回答,我使用Objective C和Xcode編程,明天我會嘗試在我的項目中使用您的信息,並讓您知道... 感謝您的幫助 – Blue

+0

@Blue您應該真的改變您的問題上的標籤。 iOS!= Objective-C,Xcode同時使用Objective-C和Swift。不過,我添加了一個Objective-C實現,並要求對您的問題進行編輯以包含Objective-C標記。 – JAL

+0

@藍色的任何更新或問題?如果您需要任何其他幫助,請告訴我。 – JAL

2

//斯威夫特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&regionCode=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() 









}