iosfan iosfan - 4 months ago 99
Swift Question

Why sending message crashes when clicking button for third time?

I set up sending message to phone numbers in my project and works fine. I click the

,iPhone sending message page pops up, if I send a message or click
, it goes back. Now if I click the button for second time, nothing happens, if I click for third time, app crashes. The info in console told me to change Use afterScreenUpdates:NO to
Use afterScreenUpdates:YES
. So I added
controller.view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
in my code, but it didn't work. What needs to change here?

in console:

Cannot snapshot view (<UIKeyboardImpl: 0x101a224f0; frame = (0 0; 320 216); layer = <CALayer: 0x170622880>>) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES.

My code:

import UIKit
import MessageUI

class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {

let messageVC = MFMessageComposeViewController()

var phoneNumber = ""

override func viewDidLoad() {

messageVC.messageComposeDelegate = self

@IBAction func sendMessageTapped(_ sender: AnyObject) {

let recipient = self.phoneNumber // I get self.phonenumber from other code, no problem.

messageVC.body = ""
messageVC.recipients = [recipient]

self.present(messageVC, animated: true, completion: nil)


func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
// I added this line to fix, didn't work.
// controller.view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)

switch result.rawValue {

case 0 :

print("Sending Message cancelled")

messageVC.dismiss(animated: true, completion: nil)

case 1:

print("Message sent")
messageVC.dismiss(animated: true, completion: nil)

case 2:

print("Sending message failed")
messageVC.dismiss(animated: true, completion: nil)




I haven't used the MFMessageComposeViewController personally, but looking at the error I can make a guess that it might not like being presented more than once. Have you tried only creating the MFMessageComposeViewController instance when you are about to show it instead of keeping a reference to it in memory and reusing it?