2017-10-13 63 views
1

我正在尝试实施Google Vision OCR请求。这里是我的代码,Google Vision - 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,变为true。 API在Postman上运行良好。 请让我知道如果我缺少的东西,任何帮助将不胜感激。

谢谢

回答

1

找你发送的“图像”和“特征”不同的阵列。

按照文档请求体应该是如下,

func getPOSTBody(base64: String) -> [String: Any]{ 

    let json: [String: Any] = [ 
    "requests": ["image": ["content": base64], 
       "features": [["type": "TEXT_DETECTION"]] 
        ] 
    ] 

    return json 
} 
+0

谢谢..!有用 –

相关问题