使用 Swift 3.0 调用 Google Cloud Natural Language API

Making call to Google Cloud Natural Language API using Swift 3.0

我正在尝试根据 Swift 中的代码 https://cloud.google.com/natural-language/reference/rest/v1/documents 向 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)
        }) }

    }


}

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

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

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

人气:

协议here。例如:

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

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "Enjoy your vacation!"
  }
}

实体:

协议here。例如:

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

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "President Obama is speaking at the White House."
  }
}

语法:

协议here。例如:

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

{
  "encodingType": "UTF8",
  "document": {
    "type": "PLAIN_TEXT",
    "content": "Hello, world!"
  }
}

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"
]