是我的搜索引擎出了问题还是其他问题?尝试更改我的API密钥。还设置了断点以查看我的nil值是否来自“ let session = ..”中的错误。没有关于做什么的任何线索。
googleSearch(term: "George Bush") { results in
print(results) }
}
func googleSearch(术语:字符串,回调:@转义([[(标题:字符串,网址:字符串)]?)->无效){ let urlString = String(格式:“ https://cse.google.com/cse?cx=016628067786358079133:2gm9usqzouc”,术语,Constants.searchEngineId,Constants.apiKey) 让encodeUrl = urlString.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)
guard let url = URL(string: encodedUrl ?? urlString) else {
print("invalid url \(urlString)")
return
}
let request = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "GET"
request.setValue(Constants.bundleId, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
let session = URLSession.shared
let datatask = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard
error == nil,
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
else {
callback(nil)
return
}
guard let items = json?["items"] as? [[String : Any]], items.count > 0 else {
print("no results")
return
}
callback(items.map { ($0["title"] as! String, $0["formattedUrl"] as! String) })
}
datatask.resume()
}
}