简体   繁体   中英

Cannot convert value of type 'UIImage?' to expected argument type '[Any]'

I am trying to send an image using a share button

I have an image in the UIViewcontroller called self.image

func share(_ sender: Any) {
    let imageToShare = self.image?
    let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    // present the view controller
    self.present(activityViewController, animated: true, completion: nil)
}

However I got the following error

Cannot convert value of type 'UIImage?' to expected argument type '[Any]'

Could it be that this has something to do with the optional value type of self.image? How do I make it non-optional while the function doesnt crash when someone click the button?

activityItems is expecting to get an Array. So you could make imageToShare non optional and send it as an Array (that contains only this image).

  1. Make it non-optional using if let
  2. Make an Array that contains this image using [imageToShare]

The complete solution would be:

if let imageToShare = self.image? {
            let activityViewController = UIActivityViewController(activityItems: [imageToShare], applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view
            // present the view controller
            self.present(activityViewController, animated: true, completion: nil)
        }

If you're going to comprehend the error that says:

Cannot convert value of type 'UIImage?' to expected argument type '[Any]'

It literally says the type (optional or not!) is not the expected [Any] type. Since a UIImage can be Any , how about you try let imageToShare = [self.image] ?

In that case, you have [Any?] type. An Any? object in an Array . Now if it still complains about the optional thing (it probably will), which you already know, then unwrap that object safely in any way you want, to make it [Any] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM