This question already has answers here:
Swift 3 How to display a confirmation screen based on MFMailComposeResult email screen
(2 answers)
Closed 5 years ago.
my problem is that I programmed emailwindow and it does send emails, but when they are send or I want to close the window there´s nothing that happens.
Thats my code:
import Foundation
import UIKit
import MessageUI
class ContactViewController: UIViewController, MFMailComposeViewControllerDelegate, UIAlertViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
let mail = MFMailComposeViewController()
#IBAction func email(_ sender: Any) {
if !MFMailComposeViewController.canSendMail() {
let warnung = UIAlertController(title: "Email konnte nicht gesendet werden", message: "Dein Gerät unterstützt leider keine Email-Funktion.", preferredStyle: .alert)
let action1 = UIAlertAction(title: "OK", style: .default, handler: nil)
warnung.addAction(action1)
self.present(warnung, animated: true, completion: nil)
return
} else {
mail.mailComposeDelegate = self
mail.setToRecipients(["team#example.com"])
mail.setSubject("Message to you")
mail.setMessageBody("Hello,\n", isHTML: false)
present(mail, animated: true, completion: nil)
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWithResult result: MFMailComposeResult, error: NSError?) {
mail.dismiss(animated: true, completion: nil)
print("Yes!")
}
}
}
}
Here´s a screenshot of the mail window :
Just click on this link!
#IBAction func email(_ sender: Any) {
if !MFMailComposeViewController.canSendMail() {
let warnung = UIAlertController(title: "Email konnte nicht gesendet werden", message: "Dein Gerät unterstützt leider keine Email-Funktion.", preferredStyle: .alert)
let action1 = UIAlertAction(title: "OK", style: .default, handler: nil)
warnung.addAction(action1)
self.present(warnung, animated: true, completion: nil)
return
} else {
mail.mailComposeDelegate = self
mail.setToRecipients(["team#example.com"])
mail.setSubject("Message to you")
mail.setMessageBody("Hello,\n", isHTML: false)
present(mail, animated: true, completion: nil)
}
}
}
func mailComposeController(_ controller: MFMailComposeViewController,
didFinishWithResult result: MFMailComposeResult, error: NSError?) {
mail.dismiss(animated: true, completion: nil)
print("Yes!")
}
Related
I have a viewcontroller with navigation controller. I have button for uploading images.But after pressing the button it doesn't popup the alert for camera or photo library options although i have written codes for alert. Why doesn't the alert popup appear? I have also given Privacy - Photo Library Usage Description in info.plist. My code is given :
import UIKit
import Alamofire
class ProfilePicController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = UIImagePickerController()
#IBOutlet weak var uploadPic: UIButton!
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
profilePic.layer.cornerRadius = profilePic.frame.size.width / 2
profilePic.clipsToBounds = true
// Do any additional setup after loading the view.
}
#IBAction func uploadPic(_ sender: Any) {
print("image add")
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("Camera selected")
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
})
alert.addAction(UIAlertAction(title: "Photo library", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("Photo selected")
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
})
self.present(self.imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
profilePic.image = selectedImage
// self.savePic()
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
//Alert.swift file
import UIKit
class Alert {
class func showBasic(title: String ,message: String , vc: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(defaultAction)
vc.present(alert, animated: true, completion: nil)
}
}
Actually you don't present the alert
#IBAction func uploadPic(_ sender: Any) {
print("image add")
let alert = UIAlertController(title: nil, message: "Choose your source", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Camera", style: .default) { (result : UIAlertAction) -> Void in
print("Camera selected")
self.imagePicker.sourceType = .camera
self.present(self.imagePicker, animated: true, completion: nil)
})
alert.addAction(UIAlertAction(title: "Photo library", style: .default) { (result : UIAlertAction) -> Void in
print("Photo selected")
self.imagePicker.sourceType = .photoLibrary
self.present(self.imagePicker, animated: true, completion: nil)
})
self.present(alert, animated: true, completion: nil)
}
I am tying to have my app take a users input to format a text message so that they can connect to an external device in the proper format through text. I have the initial setup text message working but if the user wishes to delete the geo-fence (the initial text message is responsible for setting it) they need to send a different text message however the Messages screen is automatically cancelled when called.
#IBAction func addGeoFencePushed(_ sender: Any) {
if(!geoFenceIsEnabled()){
let alertController = UIAlertController(title: nil, message: "How large would you like the geofence to be?", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let field = alertController.textFields?[0] {
// store your data
ALGlobal.sharedInstance.globalDefaults.set(field.text! as String, forKey: "geoFenceSize")
let rad = Double(field.text!)
ALGlobal.sharedInstance.geoFenceRadius = rad!
self.buttonSetting = 1
self.toggleButton()
self.drawGeoFence(radius: rad!)
self.turnOnFenceText(radius: Int(rad!))
} else {
// user did not fill field
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "Feet"
textField.keyboardType = .numberPad
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
else{
// create the alert
let alert = UIAlertController(title: "Confirm", message: "Are you sure you want to remove the geo-fence?", preferredStyle: UIAlertControllerStyle.alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
alert.dismiss(animated: true, completion: nil)
self.removeGeoFence()
}
alert.addAction(confirmAction)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
This is what is responsible for determining which text message to display.
func removeGeoFence(){
self.turnOffFenceText()
ALGlobal.sharedInstance.globalDefaults.removeObject(forKey: "geoFenceSize")
ALGlobal.sharedInstance.geoFenceRadius = 0
self.buttonSetting = 0
self.toggleButton()
self.clearMap()
}
func turnOnFenceText(radius: Int){
let radiusConverted = Int(radius / 3)
messageVC.body = "G1,1,0,\(radiusConverted)M"
messageVC.recipients = [ALGlobal.sharedInstance.globalDefaults.object(forKey: "devicePhoneNumber") as! String]
self.present(messageVC, animated: true, completion: nil)
}
func turnOffFenceText(){
messageVC.body = "G1,0"
messageVC.recipients = [ALGlobal.sharedInstance.globalDefaults.object(forKey: "devicePhoneNumber") as! String]
self.present(messageVC, animated: true, completion: nil)
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
switch (result.rawValue) {
case MessageComposeResult.cancelled.rawValue:
print("Message was cancelled")
messageVC.dismiss(animated: true, completion: nil)
case MessageComposeResult.failed.rawValue:
print("Message failed")
messageVC.dismiss(animated: true, completion: nil)
case MessageComposeResult.sent.rawValue:
print("Message was sent")
messageVC.dismiss(animated: true, completion: nil)
//self.dismiss(animated: true, completion: nil)
default:
break;
}
}
And these are the message controllers. When removeGeoFence() is called the console prints out "Message was cancelled" and the Messages app never opens and I can't figure out why.
You need to recreate the messageVC after you dismiss it otherwise your trying to reopen a dismissed view and that results in a black screen so in the turnOnFenceText() and turnOffFenceText() I reinitialized the messageVC:
func turnOnFenceText(radius: Int){
messageVC = MFMessageComposeViewController()
messageVC.messageComposeDelegate = self;
let radiusConverted = Int(radius / 3)
messageVC.body = "G1,1,0,\(radiusConverted)M"
messageVC.recipients = [ALGlobal.sharedInstance.globalDefaults.object(forKey: "devicePhoneNumber") as! String]
self.present(messageVC, animated: true, completion: nil)
}
func turnOffFenceText(){
messageVC = MFMessageComposeViewController()
messageVC.messageComposeDelegate = self;
messageVC.body = "G1,0"
messageVC.recipients = [ALGlobal.sharedInstance.globalDefaults.object(forKey: "devicePhoneNumber") as! String]
self.present(messageVC, animated: true, completion: nil)
}
That fixed the problem
I have followed peoples code on sending an email on swift and the problem is on my phone, the send button is greyed out. What do I do? Here is my code and a picture of the problem on my phone.
The Problem On My Phone, The Send Button Is Greyed Out.
import UIKit
import MessageUI
class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {
#IBAction func sendEmail(_ sender: Any)
{
let mailComposeViewController = configureMailController()
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
showMailError()
}
}
func configureMailController() -> MFMailComposeViewController
{
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["abc#gmail.com"])
mailComposerVC.setSubject("Gamifiction")
mailComposerVC.setMessageBody("Hey, Check Out My Game", isHTML: false)
return mailComposerVC }
func showMailError()
{
let sendMailErrorAlert = UIAlertController(title: "Could not send email", message: "Your device could not send email", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil)
sendMailErrorAlert.addAction(dismiss)
self.present(sendMailErrorAlert, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
I'm using a table view that has a cell that says "Send Us Feedback." It opens up the email application with preset information to be sent. I can send the email and/or cancel it, but when I cancel it the first time, stay on the table view, tap the cell again to open the email, I can't cancel it again. It just stays on the email view.
Suggestions?
My code is below:
import UIKit
import MessageUI
class FeedbackViewController: UITableViewController, MFMailComposeViewControllerDelegate {
let mailComposerVC = MFMailComposeViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 && indexPath.row == 0
{
let alertController = UIAlertController(title: "Rate Us", message: "\nAre you enjoying our app? Please rate us in the app store!\n\nElse if you know of ways we can make our app better, please send us feedback so we can improve the experience for you!\n\nThank you!\n\nTimmy Caish", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Rate on iTunes", style: .Default, handler: {
(action: UIAlertAction!) -> Void in
UIApplication.sharedApplication().openURL((NSURL(string: "http://google.com")!))
print("Rate us alert button worked.")
print("Send to iTunes")
}))
alertController.addAction(UIAlertAction(title: "Send Us Feedback", style: .Default, handler: {
(action: UIAlertAction!) in
print("Rate Us feeback button worked.")
let mailComposeViewController = self.configureMailComposeViewController()
if MFMailComposeViewController.canSendMail()
{
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
}
else
{
self.showSendMailErrorAlert()
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction) in
print("Rate us cancel button worked.")
print("Rate us")
}))
presentViewController(alertController, animated: true, completion: nil)
}
if indexPath.section == 0 && indexPath.row == 1
{
let mailComposeViewController = configureMailComposeViewController()
if MFMailComposeViewController.canSendMail()
{
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
}
else
{
self.showSendMailErrorAlert()
}
print("Send us feedback")
}
}
func configureMailComposeViewController() -> MFMailComposeViewController {
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(["developer.timmy#gmail.com"])
mailComposerVC.setSubject("Weather Simplicity Feedback")
mailComposerVC.setMessageBody("Hello,\n\nI would like to share the following feedback...\n\n", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertController(title: "Error", message: "Your device could not send the email. Check your email configurations and try again.", preferredStyle: UIAlertControllerStyle.Alert)
let okay = UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)
sendMailErrorAlert.addAction(okay)
self.presentViewController(sendMailErrorAlert, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
switch result {
case MFMailComposeResultCancelled:
print("Cancelled mail")
break
case MFMailComposeResultSent:
print("Message sent")
break
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Try creating a new mailViewController only when you need it in didSelectRow rather than at the creation of the view controller. This will ensure it is clean each time and is not created unless needed and may fix the problem of the second cancel not working.
I have tried several ways to use UIAlertController,instead of UIAlertView, but I cannot make the alert go. Thanks in advance for any further suggestions. I am a newbie.
UIAlertView' was deprecated in iOS 9.0: UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead
Here is my code :
import MessageUI
class SecondViewController: UIViewController,MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func sendmail(sender: UIButton) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["blabla#gmail.com"])
mailComposerVC.setSubject("App Feedback")
mailComposerVC.setMessageBody("Feature request or bug report?", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
use UIAlertController
Here a example:
//Create the AlertController
let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Do some stuff
}
actionSheetController.addAction(cancelAction)
//Create and an option action
let nextAction: UIAlertAction = UIAlertAction(title: "Next", style: .Default) { action -> Void in
//Do some other stuff
}
actionSheetController.addAction(nextAction)
//Add a text field
actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
//TextField configuration
textField.textColor = UIColor.blueColor()
}
//Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
Try something like this...
let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert)
self.presentViewController(sendMailErrorAlert, animated: true, completion: nil)
let alertController = UIAlertController(title: "Could Not Send Email
", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert)
Use UIAlertController
After initializing add actions to alertcontroller.
UIAlertCOntroller is subclass of UIViewController. So you can use self.presentViewController method show alert on current controller.