gpt4 book ai didi

ios - 使用 Swift 3.0 调用 Google Cloud Natural Language API

转载 作者:可可西里 更新时间:2023-11-01 00:48:34 30 4
gpt4 key购买 nike

我正在尝试根据此代码 https://cloud.google.com/natural-language/reference/rest/v1/documents 向 Google 的 Cloud Natural Language API 提出请求在 Swift 中,但我不能完全正确地理解语法?

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 客户端库,您必须自己处理请求(正如您已经确定的那样)。希望官方文档足以让您继续:

情绪:

协议(protocol) here .例如:

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

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

实体:

协议(protocol) here .例如:

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

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

语法:

协议(protocol) 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"
]

关于ios - 使用 Swift 3.0 调用 Google Cloud Natural Language API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403565/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com