Swift REST API调用Azure表单识别器

pu3pd22g  于 2023-11-16  发布在  Swift
关注(0)|答案(1)|浏览(135)

我正在使用以下代码调用Azure Form Recognizer REST API,用于我的iOS Swift应用中的收据模型。这不会返回任何错误代码,但响应只是空的。我也在Post Man中尝试过,也得到了空响应。
如何从这个API调用中获取数据?

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()
}

字符串
谢谢你

gjmwrych

gjmwrych1#

我发现,一旦你得到了成功响应,你必须再次调用Azure来获得Operation Location值的结果:

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

字符串
然后使用以下方法提取数据:

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)")
}

相关问题