Search code examples
iosswiftfirebase-mlkit

MLKit text detection exception -[Not A Type _cfTypeID]: message sent to deallocated instance 0x106623e20


I'm trying to create an app that detects the text in a photo taken by the device's camera using MLKit's text detection features. Below is the code in my photoOutput method, as well as the code for the method that it calls:

func photoOutput(_ output: AVCapturePhotoOutput,
                 didFinishProcessingPhoto photo: AVCapturePhoto,
                 error: Error?) {
    print("worked")
    PHPhotoLibrary.shared().performChanges( {
        let creationRequest = PHAssetCreationRequest.forAsset()
        creationRequest.addResource(with: PHAssetResourceType.photo, data: photo.fileDataRepresentation()!, options: nil)
    }, completionHandler: nil)

    let cgImage = photo.cgImageRepresentation()!.takeRetainedValue()
    print(cgImage)
    let orientation = photo.metadata[kCGImagePropertyOrientation as String] as! NSNumber
    let uiOrientation = UIImage.Orientation(rawValue: orientation.intValue)!
    let image = UIImage(cgImage: cgImage, scale: 1, orientation: uiOrientation)

    self.runTextRecognition(with: image)
}

func runTextRecognition(with image: UIImage) {
    let visionImage = VisionImage(image: image)
    textRecognizer.process(visionImage) { features, error in
        self.processResult(from: features, error: error)
    }
}

func processResult(from text: VisionText?, error: Error?) {
    guard error == nil, let text = text else {
        print("oops")
        return
    }

    print(text.text)

}

Whenever I run the app and take a photo, everything runs fine up until the line textRecognizer.process(visionImage). The console message is -[Not A Type _cfTypeID]: message sent to deallocated instance 0x106623e20.

Any help or suggestions would be much appreciated! Please let me know if I should include more information.


Solution

  • Never mind, I fixed this! I should have been using .takeUnretainedValue() instead .takeRetainedValue(), as ARC was releasing the CGImage object for me before I was using it.