2017-10-13 65 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

謝謝..!有用 –

相關問題