main.swift 2.3 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 Dispatch
  17. import Foundation
  18. import gRPC
  19. import OAuth2
  20. let scopes = ["https://www.googleapis.com/auth/cloud-language"]
  21. if let provider = DefaultTokenProvider(scopes: scopes) {
  22. let sem = DispatchSemaphore(value: 0)
  23. try provider.withToken { (token, error) -> Void in
  24. if let token = token {
  25. gRPC.initialize()
  26. guard let authToken = token.AccessToken else {
  27. print("ERROR: No OAuth token is available.")
  28. exit(-1)
  29. }
  30. let service = Google_Cloud_Language_V1_LanguageServiceServiceClient(address: "language.googleapis.com")
  31. service.metadata = Metadata(["authorization": "Bearer " + authToken])
  32. var request = Google_Cloud_Language_V1_AnnotateTextRequest()
  33. var document = Google_Cloud_Language_V1_Document()
  34. document.type = .plainText
  35. 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."
  36. request.document = document
  37. var features = Google_Cloud_Language_V1_AnnotateTextRequest.Features()
  38. features.extractSyntax = true
  39. features.extractEntities = true
  40. features.extractDocumentSentiment = true
  41. features.extractEntitySentiment = true
  42. features.classifyText = true
  43. request.features = features
  44. print("\(request)")
  45. do {
  46. let result = try service.annotatetext(request)
  47. print("\(result)")
  48. } catch (let error) {
  49. print("ERROR: \(error)")
  50. }
  51. }
  52. if let error = error {
  53. print("ERROR \(error)")
  54. }
  55. sem.signal()
  56. }
  57. _ = sem.wait()
  58. } else {
  59. print("Unable to create default token provider.")
  60. }