2017-06-21 41 views
1
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

    let urlRequest = URLRequest(url: URL(string: "https://www.googleapis.com/youtube/v3/channels?part=id&forUsername=\(searchBar.text!.replacingOccurrences(of: " ", with: "%20"))&key=1234")!) 

    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in 

     if error == nil { 
      do { 
       let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] 

       if let items = json["items"] as? [String : AnyObject] { 
         if let id = items["id"] as? Int { 
          self.id = id 
        } 
       } 


       if let _ = json["error"] { 
        self.exists = false 
       } 

       DispatchQueue.main.async { 
        if self.exists{ 

         print("\(self.id)") 
        }else { 

         self.exists = true 

        } 
       } 


      } catch let jsonError { 
       print(jsonError.localizedDescription) 
      } 
     } 
    } 
    task.resume() 
} 

我想從谷歌分析得到的Youtube頻道ID但它口口聲聲說「無」。我不知道我做錯了什麼,因爲我的網站上的所有內容都是一樣的!請幫忙!由於谷歌分析零誤差的Xcode迅速

回答

0

當我用你的代碼,我回來了JSON是

{ 
"kind": "youtube#channelListResponse", 
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/uX-2P6nRpmv4I_ZWtiIyofqF5ss\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 5 
}, 
"items": [ 
    { 
    "kind": "youtube#channel", 
    "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/3W7RccGn0o-nTtgCGrEvd-AbX6Y\"", 
    "id": "UCfpqR6vgT_mzWrbXcTYxL8w" 
    } 
] 
} 

所以,items["id"]不是int。嘗試

if let id = items["id"] as? String 

代替

此外,改變self.id爲String。

更新:

此外,

if let items = json["items"] as? [String : AnyObject] { 

不會起作用,因爲項目是字典的數組。

你需要

if let items = json["items"] as? [[String : AnyObject]] { 

然後,

if let id = items[0]["id"] as? String 

你或許應該檢查items.count,但你可以做到這一點,一旦你得到這個工作。

+0

我仍然是「無」。 –

+0

零是什麼第一件事? json [「items」]是什麼? [字符串:AnyObject]'零? –

+0

不是id是零! 'print(「\(self.id)」)'nill –