gpt4 book ai didi

ios - Google Analytics 零错误 xcode swift

转载 作者:行者123 更新时间:2023-11-28 08:07:32 26 4
gpt4 key购买 nike

 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 channel id,但它一直显示 “nil”。我不确定我做错了什么,因为我网站上的一切都一样!请帮忙!谢谢

最佳答案

当我使用你的代码时,我得到的 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 更改为字符串。

更新:

此外,

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

不会工作,因为 items 是一个字典数组。

你需要

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

然后,

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

您可能应该检查 items.count,但一旦您开始工作就可以这样做。

关于ios - Google Analytics 零错误 xcode swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com