1
GoogleビジョンOCRリクエストを実装しようとしています。ここに私のコードは、Googleビジョン - OCR - リクエストで画像と機能を指定する必要があります
func performImageRecognition(image: UIImage){
//1. Convert Image into base64 encoding
let imageData: Data = UIImageJPEGRepresentation(image, 1.0)!
let encodedString: String = imageData.base64EncodedString()
//2. Request Body for Vision OCR
let postBody: [String: Any] = getPOSTBody(base64: encodedString)
//3. API Call
AppDelegate.makeRequest(url: Request.url, requestBody: postBody, completionHandler: {
data, response, error in
print(error!)
do{
let dictionary = try JSONSerialization.jsonObject(with: data!, options: [])
print(dictionary)
self.activityindicator.stopAnimating()
}catch{
print("Error Parsing Data: \(error)")
}
})
}
/*
* Request Body
*/
func getPOSTBody(base64: String) -> [String: Any]{
let json: [String: Any] = [
"requests": [["image": ["content": base64]],
["features": [["type": "TEXT_DETECTION"]]]
]
]
return json
}
リクエスト・ハンドラ
class func makeRequest(url: URL, requestBody: [String: Any],completionHandler: @escaping (Data?, Int?, String?) -> Void){
var requestData: Data!
var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
// 1. Serialize the request body to Data
do{
requestData = try JSONSerialization.data(withJSONObject: requestBody, options: [])
}catch{
print("ERROR:: Generating data from JSON Body : \(error) ")
}
// 2. Setting up the required Header Fields
urlRequest.httpBody = requestData
urlRequest.addValue("\(requestData.count)", forHTTPHeaderField: "Content-Length")
urlRequest.addValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
// 3. Creating the Session
let session = URLSession(configuration: .default)
let dataTask: URLSessionDataTask = session.dataTask(with: urlRequest, completionHandler: {
data, response, error in
if (error != nil){
print("Error is: \(error?.localizedDescription ?? "None")")
return
}
let resp = response as? HTTPURLResponse
DispatchQueue.main.async {
completionHandler(data, resp?.statusCode ?? 0, error?.localizedDescription ?? "None")
}
})
dataTask.resume()
}
問題は、 "不正な要求、400のステータス、要求は画像や特徴を指定する必要があります。" になっています。
私はisValidJSONObject
のリクエストボディをチェックしています。 APIはPostmanでうまく動作しています。 私は何かが不足している場合は、私に教えてください、任意のヘルプが評価されます。
は、 "画像" と "機能" のための別の配列を送信
おかげで...!できます –