티스토리 뷰

반응형

 

안녕하세요 Sulkun 입니다.

 

이번에 개발하면서 문의하기 기능을 넣어 달라고해서

 

부랴부랴 넣는데 생각 보다 쉽더군요

 

아래 보이시는 간단하는 소스와 주위사항만 보신다면

 

저처럼 문제 없이 하실수 있다고 생각합니다..

 

 

 

 

 

먼저 Import MessageUI 를 해줘야합니다.

 

import MessageUI

class ViewController: UIViewController {

 

 

이후 메일 보내기 Action 을 할수 있는 버튼을 생성하시고 내부 코딩을 해주세요

 

    @IBAction func SendToEmailAction(_ sender: Any) {
        if MFMailComposeViewController.canSendMail() {
            EmailProc()
        }else {
            print("Mail services are not available")
            let alert = UIAlertController(title: "알림", message: "Do you want email setting?", preferredStyle: UIAlertController.Style.alert)
            let okAction = UIAlertAction(title: "OK", style: .default) { (action) in
                //설정으로 바로 가기
                if let url = URL(string: "mailto://azimov@demo.com") {
                    if UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.openURL(url)
                    } else {
                        print("Cannot open URL")
                    }
                }
            }
            let cancelAction = UIAlertAction(title: "cancel", style: .cancel) { (action) in
                //설정으로 바로 가기
            }
            
            alert.addAction(okAction)
            alert.addAction(cancelAction)
            present(alert, animated: false, completion: nil)
        }
        
    }

 

 

 

위에 소스를 간단하게 설명하자면

 

먼저  MFMailComposeViewController.canSendMail() 를 이용해서 메일을 보낼수 있는 상황인지 먼저 체크를 해야됩니다.

 

저분을 빼고 할시 뜨거운 Error를 보실수 있을실 꺼에요.

 

두번째는 연결이 안되어 있을시 메일 설정창으로 이동하시겠습니까라는 문구와 shared open을 이용해서 메일창으로 이동했습니다.

 

그리고 마지막으로 메일 셋팅이 되어 있을시 

 

    func EmailProc() {
        let picker = MFMailComposeViewController()
        picker.mailComposeDelegate = self
        
        // Configure the fields of the interface.
        picker.setToRecipients(["exampleEmail@email.com"])
        picker.setSubject("Message Subject")
        picker.setMessageBody("", isHTML: true)
        
        present(picker, animated: true, completion: nil)
    }

저렇게 하면 메일 쓰는 창으로 내용이 기입되어져요. 

 

Body 에 구지 글을 안쓴이유는 메일 보내는 창에서 쓰는게 더 편해서....

 

아 참. Finish 됬을때는 extension 했습니다.

 

extension ViewController : MFMailComposeViewControllerDelegate {
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        //Check the result or perform other tasks.
        
        // Dismiss dismiss(animated: true, completion: nil)
        dismiss(animated: true, completion: nil)
    }
}

 

마지막으로 주위사항

 

1) iOS 디바이스의 Email 로그인이 되어 있어야 합니다.

2) iOS 디바이스에서만 동작합니다. (시뮬레이터 동작 안함)

반응형
댓글