Computer >> 컴퓨터 >  >> 프로그램 작성 >> IOS

Swift를 사용하여 이메일에 첨부 파일을 보내는 방법은 무엇입니까?


애플리케이션을 사용하여 iPhone 장치에서 이메일을 보내려면 iOS SDK의 MessageUI 프레임워크를 가져와야 합니다. 애플리케이션에서 프레임워크를 가져온 후 뷰 컨트롤러에 버튼을 끌어다 놓습니다. 해당 버튼에 대해 빈 작업을 추가합니다.

이제 뷰 컨트롤러에 다음 코드를 추가하세요.

funccomposeEmail(to email: String,subject: String,Body: String) {
   if( MFMailComposeViewController.canSendMail()) {
      letmailComposer = MFMailComposeViewController()
      mailComposer.mailComposeDelegate = self
      mailComposer.setToRecipients([email])
      mailComposer.setSubject(subject)
      mailComposer.setMessageBody(Body, isHTML: true)
      letpathPDF = "\(NSTemporaryDirectory())result.pdf"
      if let fileData = NSData(contentsOfFile: pathPDF) {
         mailComposer.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "result.pdf")
      }
      self.present(mailComposer, animated: true, completion: nil)
      } else {
         print("email is not supported")
      }
   }
   funcmailComposeController(_ didFinishWithcontroller:
   MFMailComposeViewController, didFinishWith result:
   MFMailComposeResult, error: Error?) {
      self.dismiss(animated: true, completion: nil)
   }
}

방금 만든 버튼의 작업 내에서 이 메서드를 호출합니다.

@IBActionfuncactionButtonOne(_ sender: Any) {
composeEmail(to: "ashish@xy.com", subject: "Saying Hi", Body: "Hey there, hope you are doing well.")
}

위의 코드를 실행하고 추가한 버튼을 누르면 다음과 같은 결과가 나옵니다.

Swift를 사용하여 이메일에 첨부 파일을 보내는 방법은 무엇입니까?

주의해야 할 몇 가지 사항이 있습니다 -

  • iPhone의 메일 애플리케이션에 하나 이상의 계정이 추가되었는지 확인하십시오.

  • 업로드하려는 주소에 로컬로 PDF가 저장되어 있는지 확인하십시오.