iosswiftazureazure-form-recognizer

Swift REST API call to Azure Form Recognizer


I am using the following code to make a call to the Azure Form Recognizer REST API for the receipt model in my iOS Swift app. This doesn't return any error codes, but the response is just empty. I have also tried this in Post Man and also get an empty response.

How do I get the data back from this API call?

func recognizeReceipt(imageData: Data, apiKey: String, endpoint: String) {
    
    let urlString = "\(endpoint)/formrecognizer/documentModels/prebuilt-receipt:analyze?api-version=2022-08-31"
    
    guard let url = URL(string: urlString) else {
        print("Invalid URL")
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue(apiKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
    request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
    request.httpBody = imageData
    
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("Error: \(error.localizedDescription)")
            return
        }
        
        guard let httpResponse = response as? HTTPURLResponse else {
            print("Invalid response")
            return
        }
        
        if (200...299).contains(httpResponse.statusCode) {
            if let data = data {
                // Process the response data
                let resultString = String(data: data, encoding: .utf8)
                print("Result: \(resultString ?? "")")
            }
        } else {
            print("API request failed. Status code: \(httpResponse.statusCode)")
        }
    }
    
    task.resume()
}

Thank you


Solution

  • I found that once you get the success response, you must then make another call to Azure to get the results with the Operation Location value:

    if let operationLocationVal = headers["operation-location"] as? String {
        print("Operation Location: \(operationLocationVal)")
    }
    

    Then extract the data using:

    do {
                        
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
        let analyzeResult = json["analyzeResult"] as? [String: Any],
        let documents = analyzeResult["documents"] as? [Any],
        let document = documents.first as? [String: Any] {
    
        //Extract data from document here
        if let fields = document["fields"] as? [String: Any] {
            //Get total value                    
            if let total = fields["Total"] as? [String: Any],
            let totalValueNumber = total["valueNumber"] as? Double {
                print("Total Value Number: \(totalValueNumber)")
            } else {
                print("Total value unknown")
            }
        }
    } catch {
        print("Error: \(error)")
    }