swift - 无法将类型 'Data' 的值转换为指定类型 'Data'

标签 swift xcode sms xcode9-beta messageui

我有以下代码,它截取用户屏幕的屏幕截图,并允许他们通过 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/

相关文章:

regex - Swift 3 replacingOccurrences 正则表达式

ios - 将 ViewController 缩小为圆形过渡 - swift

ios - 大型 uitableview(1000 行)在 reloadData() 上卡住

objective-c - 许多 bundle 的组织(如 System Preferences.app)

ruby-on-rails - 使用短信网关发送/接收短信有哪些优势

java - 发送短信然后发送电子邮件

ios - 在 Swift 中按名称获取实例变量

ios - 如何解释 Fabric 崩溃和 Xcode 崩溃之间的巨大差异?

c - Xcode c bad_acces 代码 2 错误

iphone - 如何从 iPhone 应用程序访问和打开 iPhone 的 SMS API