我正在尝试使用共享按钮发送图像
我在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的可选值类型有关吗? 当某人单击该按钮时该功能不会崩溃时,如何使其变为非可选?
答案 0 :(得分:2)
activityItems
期望得到一个数组。因此,您可以将imageToShare
设置为非可选,并将其作为数组发送(仅包含此图像)。
if let
使其为非可选[imageToShare]
完整的解决方案是:
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]
。