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