我返回nil,为什么我的get request / google search收到错误消息

时间:2019-04-28 20:34:52

标签: swift get google-search google-search-api get-request

是我的搜索引擎出了问题还是其他问题?尝试更改我的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()
        }
}

0 个答案:

没有答案