main.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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/cloud-language"]
  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 service = Google_Cloud_Language_V1_LanguageServiceService(address:"language.googleapis.com")
  30. service.metadata = Metadata(["authorization":"Bearer " + authToken])
  31. var request = Google_Cloud_Language_V1_AnnotateTextRequest()
  32. var document = Google_Cloud_Language_V1_Document()
  33. document.type = .plainText
  34. 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."
  35. request.document = document
  36. var features = Google_Cloud_Language_V1_AnnotateTextRequest.Features()
  37. features.extractSyntax = true
  38. features.extractEntities = true
  39. features.extractDocumentSentiment = true
  40. features.extractEntitySentiment = true
  41. features.classifyText = true
  42. request.features = features
  43. print("\(request)")
  44. do {
  45. let result = try service.annotatetext(request)
  46. print("\(result)")
  47. } catch (let error) {
  48. print("ERROR: \(error)")
  49. }
  50. }
  51. if let error = error {
  52. print("ERROR \(error)")
  53. }
  54. sem.signal()
  55. }
  56. _ = sem.wait(timeout: DispatchTime.distantFuture)
  57. } else {
  58. print("Unable to create default token provider.")
  59. }