我有以下代码,它截取用户屏幕的屏幕截图,并允许他们通过 SMS 将其作为附件发送给 friend 。
func sendSmsToFriend() {
UIGraphicsBeginImageContext(view.frame.size)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let screenshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if MFMessageComposeViewController.canSendText() && MFMessageComposeViewController.canSendAttachments() {
let smsController = MFMessageComposeViewController()
smsController.body = "Can you please tell me what colour this is?"
let screenshotImageData: Data = UIImagePNGRepresentation(screenshotImage!)!
smsController.addAttachmentData(screenshotImageData, typeIdentifier: "data", filename: "screenshotImage.png")
smsController.messageComposeDelegate = self
self.present(smsController, animated: true, completion: nil)
} else {
print("User cannot send texts or attachments")
}
}
上面的代码在一个单独的项目上运行良好,在最新稳定的 Xcode 公开版本上。
我试图将代码添加到将在最新的 iOS(我相信是 11.3 beta 2)上运行的项目,因此我正在使用 Xcode 9.3 Beta 2(2018 年 2 月 6 日发布)进行开发。
这是测试版中的错误吗?
我收到的错误是针对该行的:
let screenshotImageData: Data = UIImagePNGRepresentation(screenshotImage!)!
随后也在下面的行中。
获得:
无法将类型“Data”的值转换为指定类型“Data”
最佳答案
错误信息
Cannot convert value of type 'Data' to specified type 'Data'
表示您的应用程序中定义了另一种 Data
类型
或一些包含的模块,它与 struct Data
冲突
基础框架。这是一个独立的示例来演示
问题:
import Foundation
struct Data { }
let d: Data = "abc".data(using: .utf8)!
// Cannot convert value of type 'Data' to specified type 'Data'
您始终可以在模块名称前加上显式引用该模块中的类型:
let screenshotImageData: Foundation.Data = UIImagePNGRepresentation(screenshotImage!)!
但实际上你根本不需要类型注释,用
let screenshotImageData = UIImagePNGRepresentation(screenshotImage!)!
screenshotImageData
的类型自动从
右侧的表达式(如 Foundation.Data
)。
当然最好避免这种歧义而不是
定义另一个 Data
类型。
关于swift - 无法将类型 'Data' 的值转换为指定类型 'Data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48885639/