GarySabo
GarySabo

Reputation: 6680

Making call to Google Cloud Natural Language API using Swift 3.0

I'm trying to form my request to Google's Cloud Natural Language API based on this code https://cloud.google.com/natural-language/reference/rest/v1/documents in Swift, but I can't quite get the syntax right?

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)
        }) }

    }


}

Upvotes: 2

Views: 2538

Answers (1)

Graham Polley
Graham Polley

Reputation: 14781

First of all, you're calling the vision API in your base URL. You should be calling the Natural Language API, not vision:

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

Then, it depends on what you are trying to do i.e. sentiment, entities, or syntax analysis. As there is no iOS client lib, you'll have to handroll the request yourself (as you've already identified). Hopefully, the official docs have enough to get you going:

Sentiment:

Protocol here. For example:

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

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

Entities:

Protocol here. For example:

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

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

Syntax:

Protocol here. For example:

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

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

Swift 3.0 equivalent would be something like this:

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

Upvotes: 5

Related Questions