Implementing Google custom search API in iOS

后端 未结 2 767
忘掉有多难
忘掉有多难 2020-11-29 21:18

I went through several links in order to find the proper steps to implement google customsearchapi in an ios application and spent about 6-7 hours in that process.

<

2条回答
  •  隐瞒了意图╮
    2020-11-29 21:38

    The following provide implementation in Swift 4, of "GET" request from google custom search engine,

    let apiKey = "Your api key here"
    let bundleId = "com.Your uniqueBundleId here"
    let searchEngineId = "Your searchEngine here"
    let serverAddress = String(format: "https://www.googleapis.com/customsearch/v1?q=%@&cx=%@&key=%@","Your query here" ,searchEngineId, apiKey)
    
    
    let url = serverAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let finalUrl = URL(string: url!)
    let request = NSMutableURLRequest(url: finalUrl!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
    request.httpMethod = "GET"
    request.setValue(bundleId, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
    
    let session = URLSession.shared
    
    let datatask = session.dataTask(with: request as URLRequest) { (data, response, error) in
        do{
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                print("asyncResult\(jsonResult)")
            }
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    datatask.resume()
    

提交回复
热议问题