main.swift 2.6 KB

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