Reputation: 391
I wonder whether it is possible to send an image via message in iMessageExtension. I am developing an app where sender and receiver need to see the same image.
Basically here is DetailViewController with ImageView and ImageView.image should image sent via message.
Upvotes: 1
Views: 905
Reputation: 12206
The below code captures a view and essentially screenshots it, then shares it via iMessage. Tested this on iPhone 7 running iOS 10, works.
let name = ""
let desc = ""
if MFMessageComposeViewController.canSendText() {
let messageVC = MFMessageComposeViewController()
messageVC.messageComposeDelegate = self
if MFMessageComposeViewController.canSendAttachments() {
let img = viewToCapture.getSnapshotImage()
let imageData = UIImagePNGRepresentation(img)
messageVC.addAttachmentData(imageData!, typeIdentifier: "image/png", filename: "image.png")
} else {
print("Message can't send attachments")
}
self.present(messageVC, animated: true, completion: nil)
}
let messageComposeViewController = configuredMessageViewController(name, detail: desc)
if MFMessageComposeViewController.canSendText() {
self.present(messageComposeViewController, animated: true, completion: nil)
} else {
shareStuff.msgError()
}
Note that the above uses this UIView extension to capture the image from the screen. If this is your first extension, it's global so just put the code where ever you want (but not within a class):
public func getSnapshotImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
let snapshotImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return snapshotImage
}
Upvotes: 1
Reputation: 23634
There are a few ways to do this. If you are just trying to send a regular non-animated image you can avoid having to save temporary files to disk (which you would send by calling insertAttachment
on your conversation
) and instead use MSMessageTemplateLayout
directly. You can do something like this:
let message = MSMessage()
let layout = MSMessageTemplateLayout()
layout.image = myImage
message.layout = layout
conversation.insert(message, completionHandler: nil)
Upvotes: 1