SwiftUI Send SMS with Coordinator and UIViewControllerRepresentable

263 views Asked by At

How can I write the following code with UIViewControllerRepresentable? I want the code I write to be regular. Do you think it makes sense to write this code with UIViewControllerRepresentable?

 import MessageUI
    
    class ViewController: UIViewController, MFMessageComposeViewControllerDelegate {
    
        @IBOutlet weak var phoneNumber: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func sendText(sender: UIButton) {
            if (MFMessageComposeViewController.canSendText()) {
                let controller = MFMessageComposeViewController()
                controller.body = "Message Body"
                controller.recipients = [phoneNumber.text]
                controller.messageComposeDelegate = self
                self.presentViewController(controller, animated: true, completion: nil)
            }
        }
    
        func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
            //... handle sms screen actions
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    
        override func viewWillDisappear(animated: Bool) {
            self.navigationController?.navigationBarHidden = false
        }
    }

SMSViewController

 struct SMSViewController: UIViewControllerRepresentable {
        
        class Coordinator: NSObject, MFMessageComposeViewControllerDelegate {
            
            func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
                
            }
            var parent: MFMessageComposeViewController
            
            init(_ parent: MFMessageComposeViewController) {
                self.parent = parent
            }
        }
        
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }
        
        func makeUIViewController(context: UIViewControllerRepresentableContext<MFMessageComposeViewController>) -> MFMessageComposeViewController {
            let messageViewController = MFMessageComposeViewController()
            messageViewController.delegate = context.coordinator
            return messageViewController
        }
        func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
            
        }
    }
0

There are 0 answers