2015-11-03 81 views
3

我試圖做一些非常簡單的事情;獲得與我在您的應用中顯示的視頻結果相同的搜索結果,當您搜索Youtube.com並按Upload count排序時。Youtube API v3 search.list返回不相關的視頻Swift

幾乎一切工作正常,我可以:

  • 獲取縮略圖,標題和頻道名稱
  • 播放視頻

*上獲取每個視頻的觀看次數太多工作(我聽說你需要 來創建兩個請求?)

真正讓我困惑的是這個代碼:

var urlString = "https://www.googleapis.com/youtube/v3/search? 
part=snippet 
&fields=items(id,snippet(title,channelTitle,thumbnails)) 
&order=viewCount 
&q=\(searchBar.text) 
&type=video 
&maxResults=25&key=\(apiKey)" 

會產生這樣的結果:

enter image description here

,而不是這樣的:

*不包括播放列表

enter image description here

什麼是錯我的代碼?

func searchBarSearchButtonClicked(searchBar: UISearchBar) { 

     searchBar.resignFirstResponder() 

     // Form the request URL string. 
     var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(searchBar.text)&type=video&maxResults=25&key=\(apiKey)" 

     urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! 

     // Create a NSURL object based on the above string. 
     let targetURL = NSURL(string: urlString) 

     // Get the results. 
     performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in 
      if HTTPStatusCode == 200 && error == nil { 
       // Convert the JSON data to a dictionary object. 
       let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject> 

       // Get all search result items ("items" array). 
       let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>> 

       // Loop through all search results and keep just the necessary data. 
       for var i=0; i<items.count; ++i { 
        let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject> 
        //     let statisticsDict = items[i]["statistics"] as! Dictionary<NSObject, AnyObject> 

        // Create a new dictionary to store the video details. 
        var videoDetailsDict = Dictionary<NSObject, AnyObject>() 
        videoDetailsDict["title"] = snippetDict["title"] 
        videoDetailsDict["channelTitle"] = snippetDict["channelTitle"] 
        videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"] 
        videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"] 
        //     videoDetailsDict["viewCount"] = statisticsDict["viewCount"] 

        self.videosArray.append(videoDetailsDict) 

        // Reload the tableview. 
        self.tableView.reloadData() 

       } 

      } 
      else { 
       print("HTTP Status Code = \(HTTPStatusCode)") 
       print("Error while loading channel videos: \(error)") 
      } 

     }) 

    } 


    // MARK: Custom method implementation 

    func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) { 
     let request = NSMutableURLRequest(URL: targetURL) 
     request.HTTPMethod = "GET" 

     let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() 

     let session = NSURLSession(configuration: sessionConfiguration) 

     let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in 
      dispatch_async(dispatch_get_main_queue(), {() -> Void in 
       completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error) 
      }) 
     }) 

     task.resume() 
    } 

回答

2

這個問題其實很簡單,對我的安慰/挫折很重要。

在URL中,這是問題:

\(searchBar.text) 

searchBar.text是可選的,這就是爲什麼結果來從youtube.com搜索回不同。簡單修復:

\(searchBar.text!) 
相關問題