Reputation: 127
I am trying to display an email popup on myViewController, but I get the error
Use of unresolved identifier 'present'
on the line
present(composer, animated: true)
It is worth noting that the button is within a collectionView cell. How would I fix this error so that when I press the button an email overview will show up on the screen?
Here is my code.
import MessageUI
class MessagesViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBAction func emailButtonTapped(_ sender: Any) {
showMailComposer()
}
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else {
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["email"])
composer.setSubject("")
composer.setMessageBody("", isHTML: false)
composer.present(composer, animated: true)
present(composer, animated: true)
}
}
extension MessagesViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let _ = error {
controller.dismiss(animated: true)
}
switch result {
case .cancelled:
print("Cancelled")
case .failed:
print("Failed to send")
case .saved:
print("Saved")
case .sent:
print("Email Sent")
default:
break
}
controller.dismiss(animated: true)
}
}
Upvotes: 1
Views: 54
Reputation: 16341
The most simple way to fix this would be to pass a weak reference of the UIViewController
to the UICollectionViewCell
. Then call the present on the UIViewController
passed by weak reference instead of calling it on an instance of UICollectionViewCell
. Here's how:
In cellForItem
method:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier, for: indexPath) as! MessagesViewCell
cell.controller = self
//...
return cell
}
And in MessagesViewCell
:
class MessagesViewCell: UICollectionViewCell, MFMailComposeViewControllerDelegate {
weak var controller: UIViewController?
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else {
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["email"])
composer.setSubject("")
composer.setMessageBody("", isHTML: false)
composer.present(composer, animated: true)
controller?.present(composer, animated: true)
}
Upvotes: 1