shahin ali agharia shahin ali agharia - 1 year ago 83
Swift Question

Could not cast value of type 'UIImage'to 'NSString'

I am trying to capture image by tap on captureDoc button. But when I tap on capture button I am getting an error 'could not cast value of type UIImage to NSString'. Below is my code of action button.

@IBAction func captureDoc(sender: AnyObject) {
weak var weakSelf = self

self.scanDoc.captureImageWithCompletionHander({(imageFilePath) -> Void in
let captureImageView: UIImageView = UIImageView(image: UIImage(contentsOfFile: imageFilePath as! String))
captureImageView.backgroundColor = UIColor(white: 0.0, alpha: 0.7)
captureImageView.frame = CGRectOffset(weakSelf!.view.bounds, 0, -weakSelf!.view.bounds.size.height)
captureImageView.alpha = 1.0
captureImageView.contentMode = .ScaleAspectFit
captureImageView.userInteractionEnabled = true
let dismissTap: UITapGestureRecognizer = UITapGestureRecognizer(target: weakSelf, action: #selector(self.dismissPreview))
UIView.animateWithDuration(0.7, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .AllowUserInteraction, animations: {
captureImageView.frame = weakSelf!.view.bounds

}, completion: nil)

I am getting this error because I have an imageFilePath as an AnyObject but in the below statement we have to pass string. So I am really confused what to do. If anyone can figure it out whats the problem is.
Thank You!

UIImage(contentsOfFile: imageFilePath as! String)

Answer Source

Based on your description, you get an image back instead of the path your code expects so you can just do:

self.scanDoc.captureImageWithCompletionHander({(image) -> Void in
    let captureImageView: UIImageView = UIImageView(image: image)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download