main.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2017, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import gRPC
  18. import OAuth2
  19. let scopes = ["https://www.googleapis.com/auth/datastore"]
  20. if let provider = DefaultTokenProvider(scopes:scopes) {
  21. let sem = DispatchSemaphore(value: 0)
  22. try provider.withToken() {(token, error) -> Void in
  23. if let token = token {
  24. gRPC.initialize()
  25. guard let authToken = token.AccessToken else {
  26. print("ERROR: No OAuth token is available.")
  27. exit(-1)
  28. }
  29. let projectID = "your-project-identifier"
  30. let certificateURL = URL(fileURLWithPath:"roots.pem")
  31. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  32. let service = Google_Datastore_V1_DatastoreService(address:"datastore.googleapis.com",
  33. certificates:certificates,
  34. host:nil)
  35. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  36. var request = Google_Datastore_V1_RunQueryRequest()
  37. request.projectID = projectID
  38. var query = Google_Datastore_V1_GqlQuery()
  39. query.queryString = "select *"
  40. request.gqlQuery = query
  41. print("\(request)")
  42. do {
  43. let result = try service.runquery(request)
  44. print("\(result)")
  45. } catch (let error) {
  46. print("ERROR: \(error)")
  47. }
  48. }
  49. if let error = error {
  50. print("ERROR \(error)")
  51. }
  52. sem.signal()
  53. }
  54. _ = sem.wait(timeout: DispatchTime.distantFuture)
  55. } else {
  56. print("Unable to create default token provider.")
  57. }