2015-11-03 65 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!)