swiftxcodesmsxcode9-betamessageui

Cannot convert value of type 'Data' to specified type 'Data'


I have the following code which takes a screenshot of the user's screen and allows them to send it to a friend as an attachment via SMS.

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

The above works fine on a separate project, on the latest stable public release of Xcode.

I attempting to add the code to a project that will be running on the latest iOS (11.3 beta 2 I believe) and thus I'm using Xcode 9.3 Beta 2 (Released Feb 6th, 2018) to develop.

Is this a bug in the beta?

The error I am receiving is for the line:

let screenshotImageData: Data = UIImagePNGRepresentation(screenshotImage!)! and subsequently on the line below too.

Getting:

Cannot convert value of type 'Data' to specified type 'Data'


Solution

  • The error message

    Cannot convert value of type 'Data' to specified type 'Data'

    indicates that there is another Data type defined in your application or some included module, which conflicts with struct Data from the Foundation framework. Here is a self-contained example to demonstrate the problem:

    import Foundation
    
    struct Data { }
    
    let d: Data = "abc".data(using: .utf8)!
    // Cannot convert value of type 'Data' to specified type 'Data'
    

    You can always prepend the module name to refer to a type from that module explicitly:

    let screenshotImageData: Foundation.Data = UIImagePNGRepresentation(screenshotImage!)!
    

    But actually you don't need the type annotation at all, with

    let screenshotImageData = UIImagePNGRepresentation(screenshotImage!)!
    

    the type of screenshotImageData is inferred automatically from the expression on the right-hand side (as Foundation.Data).

    Of course it would be preferable to avoid such a ambiguity and not define another Data type.