使用 Swift 3.0 调用 Google Cloud Natural Language API

Gar*_*abo 2 nsurlrequest ios google-cloud-platform swift

我正在尝试根据此代码https://cloud.google.com/natural-language/reference/rest/v1/documents in Swift对 Google 的 Cloud Natural Language API 提出请求,但我不太明白语法对吗?

import Foundation
import SwiftyJSON

class GoogleNaturalLanguageParser {

    let session = URLSession.shared
    var googleAPIKey = "XXX"
    var googleURL: URL {
        return URL(string: "https://language.googleapis.com/v1/documents:analyzeEntities?key=\(googleAPIKey)")!
    }
    //TODO: Add document 

    private func createRequest(with text: String, handler: @escaping (String) -> Void) {
        // Create our request URL

        var request = URLRequest(url: googleURL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")

          // Build our API request
    let jsonRequest = [
        "requests": [
        ["encodingType": "UTF8",
            "document": [
                "type": "PLAIN_TEXT",
                "content": text
            ]
        ]
        ]

    ]
        let jsonObject = JSON(jsonDictionary: jsonRequest)
        //let jsonObject = JSONSerialization.jsonObject(with: jsonRequest, options: []) as? [String : Any]

        // Serialize the JSON
        guard let data = try? jsonObject.rawData() else {
            return
        }

        request.httpBody = data



        // Run the request on a background thread
        DispatchQueue.global().async { self.runRequestOnBackgroundThread(request, handler: { (result) in
            handler(result)
        }) }

    }


}
Run Code Online (Sandbox Code Playgroud)

Gra*_*ley 5

首先,您在基本 URL 中调用视觉 API。您应该调用自然语言 API,而不是视觉:

https://vision.googleapis.com/v1/documents:annotateText?key=\(googleAPIKey)

然后,这取决于您要尝试做什么,即情绪、实体或语法分析。由于没有 iOS 客户端库,您必须自己处理请求(正如您已经确定的那样)。希望官方文档足以让您开始:

情绪:

协议在这里。例如:

https://language.googleapis.com/v1/documents:analyzeSentiment?key=

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "Enjoy your vacation!"
  }
}
Run Code Online (Sandbox Code Playgroud)

实体:

协议在这里。例如:

https://language.googleapis.com/v1/documents:analyzeEntities?key=

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "President Obama is speaking at the White House."
  }
}
Run Code Online (Sandbox Code Playgroud)

句法:

协议在这里。例如:

https://language.googleapis.com/v1/documents:analyzeSyntax?key=

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "Hello, world!"
  }
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.0 等价物将是这样的:

let jsonObject: [String:Any] = [
    "document": [
        "type": "PLAIN_TEXT",
        "content": "Michelangelo Caravaggio, Italian painter, is known for the Calling of Saint Matthew."],
        "encodingType": "UTF8"
]
Run Code Online (Sandbox Code Playgroud)