无法转换“ UIImage”类型的值?到预期的参数类型“ [Any]”

时间:2019-07-19 14:01:19

标签: ios swift iphone

我正在尝试使用共享按钮发送图像

我在UIViewcontroller中有一个名为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)
}

但是我遇到以下错误

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

这可能与self.image的可选值类型有关吗? 当某人单击该按钮时该功能不会崩溃时,如何使其变为非可选?

2 个答案:

答案 0 :(得分:2)

activityItems期望得到一个数组。因此,您可以将imageToShare设置为非可选,并将其作为数组发送(仅包含此图像)。

  1. 使用if let使其为非可选
  2. 使用[imageToShare]
  3. 制作一个包含此图像的数组

完整的解决方案是:

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)
        }

答案 1 :(得分:2)

如果您要理解显示以下错误:

  

无法转换“ UIImage”类型的值?预期参数类型   '[任何]'

从字面上说类型(不是必须的!)不是预期的[Any]类型。由于UIImage可以是Any,那么您尝试let imageToShare = [self.image]呢?

在这种情况下,您的类型为[Any?]Any?中的Array对象。现在,如果它仍然抱怨(您可能已经知道的)可选内容(可能会知道),然后以您想要的任何方式安全地解包该对象,使其成为[Any]