main.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. if let provider = DefaultTokenProvider() {
  20. let sem = DispatchSemaphore(value: 0)
  21. try provider.withToken() {(token, error) -> Void in
  22. if let token = token {
  23. gRPC.initialize()
  24. guard let authToken = token.AccessToken else {
  25. print("ERROR: No OAuth token is available.")
  26. exit(-1)
  27. }
  28. let certificateURL = URL(fileURLWithPath:"roots.pem")
  29. let certificates = try! String(contentsOf: certificateURL, encoding: .utf8)
  30. let service = Google_Cloud_Language_V1_LanguageServiceService(address:"language.googleapis.com",
  31. certificates:certificates,
  32. host:nil)
  33. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  34. var request = Google_Cloud_Language_V1_AnnotateTextRequest()
  35. var document = Google_Cloud_Language_V1_Document()
  36. document.type = .plainText
  37. document.content = "The Caterpillar and Alice looked at each other for some time in silence: at last the Caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice. `Who are you?' said the Caterpillar."
  38. request.document = document
  39. var features = Google_Cloud_Language_V1_AnnotateTextRequest.Features()
  40. features.extractSyntax = true
  41. features.extractEntities = true
  42. features.extractDocumentSentiment = true
  43. features.extractEntitySentiment = true
  44. features.classifyText = true
  45. request.features = features
  46. print("\(request)")
  47. do {
  48. let result = try service.annotatetext(request)
  49. print("\(result)")
  50. } catch (let error) {
  51. print("ERROR: \(error)")
  52. }
  53. }
  54. if let error = error {
  55. print("ERROR \(error)")
  56. }
  57. sem.signal()
  58. }
  59. _ = sem.wait(timeout: DispatchTime.distantFuture)
  60. } else {
  61. print("Unable to create default token provider.")
  62. }