What are error handling patterns for Vision in Swift?

When working with the Vision framework in Swift, proper error handling is crucial for creating robust applications. Below are some common error handling patterns that developers use to manage Vision-related errors:

  • Using Do-Catch Blocks: Catch specific errors that can arise from Vision requests.
  • Optionals: Use optionals to handle cases where results might not be available due to errors.
  • Completion Handlers: Return errors in completion handlers for asynchronous Vision requests.

Here is an example of how to handle errors using a Do-Catch block when requesting face detection in a given image:

        import Vision

        func detectFaces(in image: UIImage) {
            guard let cgImage = image.cgImage else {
                print("Could not convert UIImage to CGImage.")
                return
            }

            let faceDetector = VNDetectFaceRectanglesRequest { request, error in
                if let error = error {
                    print("Face detection error: \(error.localizedDescription)")
                    return
                }
                
                // Process the results if no error occurred
                for observation in request.results as? [VNFaceObservation] ?? [] {
                    print("Detected face at \(observation.boundingBox)")
                }
            }

            let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
            do {
                try handler.perform([faceDetector])
            } catch {
                print("Error performing face detection: \(error.localizedDescription)")
            }
        }
        

Swift Vision Framework Error Handling Do-Catch Face Detection Completion Handlers