I'm using CoreML and Vision to analyze a photo taken with the camera or imported from the library. Once the photo is obtained I run some code to make sure the photo is valid and if it is it returns true otherwise it returns false. I use it like so:
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let error = error {
// display alert there is a problem
return
}
guard let imageData = photo.fileDataRepresentation(), let previewImage = UIImage(data: imageData) else {
// display alert there is a problem
return
}
if useVisionAndCoreMLToCheckIfIsImageValid(image: previewImage) {
tableData.append(previewImage)
} else {
// display alert image was not valid
}
}
The problem is there are 4 points inside the useVisionAndCoreMLToCheckIfIsImageValid function that can go wrong and I need to return false
so I can jump out of the function and if it is valid there is 1 point where it can go right and I need to return true
. But since the function returns a Bool
I keep getting errors when trying to return true
or false
at those points:
How can I get rid of the above errors?
func useVisionAndCoreMLToCheckIfIsImageValid(image: UIImage) -> Bool {
if let cgImage = image.cgImage {
let foodModel = CustomFoodModel()
guard let model = try? VNCoreMLModel(for: foodModel.model) else {
return false
}
let request = VNCoreMLRequest(model: model) { [weak self](request, error) in
if let error = error {
// 1st point - if there is an error return false
return false
}
guard let results = request.results as? [VNClassificationObservation], let topResult = results.first else {
// 2nd point - if there is a nil value here return false
return false
}
if topResult.confidence > 0.8 {
// 3rd point - if confidence is greater then 80% return true
return true
} else {
// 4th point - if confidence is less then 80% return false
return false
}
}
let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
do {
try handler.perform([request])
} catch let err as NSError {
// 5th point - if there is a try error return false
return false
}
}
}
// if the cgImage is nil return false
return false
}