How to send custom url via mail in ios
To send a custom URL via email in iOS, you can use the MFMailComposeViewController
class. Here's an example of how to do it:
-
Create a
MFMailComposeViewController
instance:let mailComposer = MFMailComposeViewController()
-
Set the subject and body of the email:
mailComposer.setSubject("Custom URL") mailComposer.setMessageBody("Check out this custom URL: \(yourCustomURL)", isHTML: false)
Replace
yourCustomURL
with the actual URL you want to send. -
Add the custom URL as an attachment:
let url = URL(string: yourCustomURL)! let urlData = try! Data(contentsOf: url) mailComposer.addAttachmentData(urlData, mimeType: "text/plain", fileName: "custom_url.txt")
This will attach the custom URL as a plain text file named "custom_url.txt".
-
Present the mail composer:
present(mailComposer, animated: true, completion: nil)
This will display the mail composer with the custom URL attached.
-
Handle the mail composer's delegate methods to handle the email sending and cancellation:
mailComposer.mailComposeDelegate = self
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { switch result { case.sent: print("Email sent successfully!") case.failed: print("Email sending failed!") case.cancelled: print("Email cancelled!") } }
Note that you need to set the `mailComposeDelegate` property to an instance of a class that conforms to the `MFMailComposeViewControllerDelegate` protocol.
Here's the complete code:
```swift
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
let yourCustomURL = "https://example.com/custom-url"
override func viewDidLoad() {
super.viewDidLoad()
let mailComposer = MFMailComposeViewController()
mailComposer.setSubject("Custom URL")
mailComposer.setMessageBody("Check out this custom URL: \(yourCustomURL)", isHTML: false)
let url = URL(string: yourCustomURL)!
let urlData = try! Data(contentsOf: url)
mailComposer.addAttachmentData(urlData, mimeType: "text/plain", fileName: "custom_url.txt")
mailComposer.mailComposeDelegate = self
present(mailComposer, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case.sent:
print("Email sent successfully!")
case.failed:
print("Email sending failed!")
case.cancelled:
print("Email cancelled!")
}
}
}
This code will send an email with the custom URL attached. When the email is sent, cancelled, or failed, the mailComposeController(_:didFinishWith: error:)
method will be called with the corresponding result.