[英]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 我在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)
}
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? 可能这与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. activityItems
期望获得一个数组。 So you could make imageToShare
non optional and send it as an Array (that contains only this image). 因此,您可以使imageToShare
为非可选,并将其作为数组发送(仅包含此图像)。
if let
使用if let
成为非可选 [imageToShare]
使用[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?' 无法转换“ UIImage”类型的值? to expected argument type '[Any]' 到预期的参数类型“ [Any]”
It literally says the type (optional or not!) is not the expected [Any]
type. 从字面上讲,该类型(是否为可选!)不是预期的[Any]
类型。 Since a UIImage
can be Any
, how about you try let imageToShare = [self.image]
? 由于UIImage
可以是Any
,那么您如何尝试let imageToShare = [self.image]
?
In that case, you have [Any?]
type. 在这种情况下,您将输入[Any?]
。 An Any?
Any?
object in an Array
. 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]
. 现在,如果它仍然抱怨(可能会)您已经知道的可选事物(然后可能会),然后以您想要的任何方式安全地将其包装,以使其成为[Any]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.