Unable to cast UIImage in swift iOS 8 Extension

后端 未结 3 1114
终归单人心
终归单人心 2021-01-02 10:48

I have a strange problem, I am trying to build an action extension that will scan barcode from the image provided. Here is the code.

override func viewDidLoa         


        
相关标签:
3条回答
  • 2021-01-02 11:10

    Getting image as

    <UIImage: 0x16ecb410>, {100, 100}
    

    It cannot be casted as NSURL and getting nil in the following expression.

    imageView.image = UIImage(data: NSData(contentsOfURL: image as NSURL)!)!
    
    0 讨论(0)
  • 2021-01-02 11:24

    U need to do like this

        if let strongImageView = weakImageView {
    
                       if let imageURL = image as? NSURL{
    
                     strongImageView.image = UIImage(data:NSData(contentsOfURL: imageURL)!)
    
                        }else{
    
                          strongImageView.image = image as? UIImage
                        }
    
                    }
    

    For Clarification I added Full Code Please refer, It worked for me

    override func viewDidLoad() {
    super.viewDidLoad()
    
    
    // Get the item[s] we're handling from the extension context.
    
    // For example, look for an image and place it into an image view.
    // Replace this with something appropriate for the type[s] your extension supports.
    var imageFound = false
    for item: AnyObject in self.extensionContext!.inputItems {
        let inputItem = item as! NSExtensionItem
        for provider: AnyObject in inputItem.attachments! {
            let itemProvider = provider as! NSItemProvider
            if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
                // This is an image. We'll load it, then place it in our image view.
                weak var weakImageView = self.imageView
                itemProvider.loadItemForTypeIdentifier(kUTTypeImage as String, options: nil, completionHandler: { (image, error) in
                    NSOperationQueue.mainQueue().addOperationWithBlock {
    
    
                    if let strongImageView = weakImageView {
    
                           if let imageURL = image as? NSURL{
    
                         strongImageView.image = UIImage(data:NSData(contentsOfURL: imageURL)!)
    
                            }else{
    
                              strongImageView.image = image as? UIImage
                            }
    
                        }
    
    
                    }
                })
    
                imageFound = true
                break
            }
        }
    
        if (imageFound) {
            // We only handle one image, so stop looking for more.
            break
        }
    }
    }
    
    0 讨论(0)
  • 2021-01-02 11:25

    the thing is that image is not UIImage, it's NSURL.

    Change code to this one:

    imageView.image = UIImage(data: NSData(contentsOfURL: image as NSURL)!)!
    
    0 讨论(0)
提交回复
热议问题