if (MFMessageComposeViewController.canSendText())
{
let controller = MFMessageComposeViewController()
controller.body = ""
controller.recipients = ["1234567890"]
controller.messageComposeDelegate = self as? MFMessageComposeViewControllerDelegate self.present(controller, animated: true, completion: nil)
}
else
{
print("Cannot send the message")
}
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult)
{
//Displaying the message screen with animation.
self.dismiss(animated: true, completion: nil)
}
while sending sms i need to attach 2 pdf i know how to add on mail but for sms i haven't found any documentation.
i have used this way for mail but how to do on messaging.
func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setSubject("Invoice PDF")
do {
let attachmentData = NSData(contentsOfFile: pdfFilePath)
mail.addAttachmentData(attachmentData! as Data, mimeType: "application/pdf", fileName: "InvoicePDF")
mail.mailComposeDelegate = self
present(mail, animated: true)
}
} else {
// show failure alert
}
}
You can export files using the UIActivityViewController:
let activityVC = UIActivityViewController(activityItems: [your-data-here], applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
If you want to limit the export options you can use the excludedActivityTypes property.
Related
I want to share both text and url to Facebook Messenger using UIActivityViewController.
But when i success send and open my Messenger, i only get url.
Is it possible send text and url to Facebook Messenger using UIActivityViewController at the same time?
Here is my code
#IBAction func sharedLink(_ sender: Any) {
let url = NSURL(string: "https://www.google.com.tw")!
let text = "test" as AnyObject
let shareObject: [AnyObject] = [text, url as AnyObject]
let vc = UIActivityViewController(activityItems: shareObject, applicationActivities: [])
vc.completionWithItemsHandler = { (type,completed,items,error) in
if completed { vc.dismiss(animated: true, completion: nil) }
}
present(vc, animated: true, completion: nil)
}
Here is my screenshot
In my case,
#IBAction func sharedLink(_ sender: Any) {
let urlString = "https://www.google.com.tw"
let url = NSURL(string: urlString)!
let text = "test" as AnyObject
let shareObject: [AnyObject] = ["\(text), \(urlString)"]
let vc = UIActivityViewController(activityItems: shareObject, applicationActivities: [])
vc.completionWithItemsHandler = { (type,completed,items,error) in
if completed { vc.dismiss(animated: true, completion: nil) }
}
present(vc, animated: true, completion: nil)
}
I have a button in my view controller, when click a button it open a document picker view controller, i have set type like KUTypePDF and KUTypeZipArchive , when i select any of these item from google drive the picker controller gets dismiss and in console it shows a long un finished strings of number that doesn't stop. I'm confused why it is showing that long string. What i want is that after i select any file from google drive it should be shown in my app. I'm getting the file url right. My code is this,
#IBAction func docsBtnTapped(_ sender: Any) {
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF),String(kUTTypeZipArchive)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .fullScreen
self.present(importMenu, animated: true, completion: nil)}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print("The Url is : /(cico)", cico)
do {
let weatherData = try NSData(contentsOf: cico, options: NSData.ReadingOptions())
print(weatherData)
let activityItems = [weatherData]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
if UI_USER_INTERFACE_IDIOM() == .phone {
self.present (activityController, animated: true, completion: {
print("Hello")
})
}
else {
let popup = UIPopoverController(contentViewController: activityController)
popup.present(from: CGRect(x: CGFloat(self.view.frame.size.width / 2), y: CGFloat(self.view.frame.size.height / 4), width: CGFloat(0), height: CGFloat(0)), in: self.view, permittedArrowDirections: .any, animated: true)
}
} catch {
print(error)
}
//optional, case PDF -> render
//displayPDFweb.loadRequest(NSURLRequest(url: cico) as URLRequest)
}
func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print(" cancelled by user")
dismiss(animated: true, completion: nil)
}
This long string come in console when i select any item of PDF or Zip file,
You can use UIDocumentInteractionController to open any kind preview from url:
Here is Simple code to open url:
var documentController:UIDocumentInteractionController!
#IBAction func btnOpenClicked(_ sender: Any) {
if let fileURL = Bundle.main.url(forResource: "icon", withExtension: "jpg") {
// Instantiate the interaction controller
self.documentController = UIDocumentInteractionController.init(url: fileURL)
self.documentController.delegate = self
self.documentController.presentPreview(animated: true)
}
else {
print("File missing! Button has been disabled")
}
}
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
This is driving me nuts. This snippet of code lets the user send an email with an image which is created within the app. Everything works perfectly except the self.dismiss(animated: true, completion: nil) - the MFMailComposeViewController won't dismiss.
I used these three possibly problems https://stackoverflow.com/a/13217443/5274566 as my start to solve the problem, but it still won't work. The controller stays despite the fact than an mail has been sent or cancel has been tapped.
The protocol implementation MFMailComposeViewControllerDelegate is added.
func mailOpen(alertAction: UIAlertAction) {
if MFMailComposeViewController.canSendMail() {
let mailcontroller = MFMailComposeViewController()
mailcontroller.mailComposeDelegate = self;
mailcontroller.setSubject("Subject")
let completeImage = newImage! as UIImage
mailcontroller.addAttachmentData(UIImageJPEGRepresentation(completeImage, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "Image")
mailcontroller.setMessageBody("<html><body><p>Message</p></body></html>", isHTML: true)
self.present(mailcontroller, animated: true, completion: nil)
} else {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send the e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "Got it!")
sendMailErrorAlert.show()
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismiss(animated: true, completion: nil)
}
}//end of mail
Issue is you have written the didFinishWithResult: delegate method inside the mailOpen function, so it will never be called and the dismissing code won't be executed ever.
func mailOpen(alertAction: UIAlertAction)
{
if MFMailComposeViewController.canSendMail()
{
let mailcontroller = MFMailComposeViewController()
mailcontroller.mailComposeDelegate = self;
mailcontroller.setSubject("Subject")
let completeImage = newImage! as UIImage
mailcontroller.addAttachmentData(UIImageJPEGRepresentation(completeImage, CGFloat(1.0))!, mimeType: "image/jpeg", fileName: "Image")
mailcontroller.setMessageBody("<html><body><p>Message</p></body></html>", isHTML: true)
self.present(mailcontroller, animated: true, completion: nil)
}
else
{
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send the e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "Got it!")
sendMailErrorAlert.show()
}
}//end of mail
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?)
{
self.dismiss(animated: true, completion: nil)
}
here:
self.dismiss(animated: true, completion: nil)
you're dismissing your own ViewController, rather than the MFMailComposeViewController
It should be:
controller.dismiss(animated: true, completion: nil)
I want to send a single message to multiple recipients using MFMessageComposeViewController, I am unable to add the second and so on recipients
here's my code :
#IBAction func sendSms(sender: AnyObject) {
if (MFMessageComposeViewController.canSendText())
{
let controller = MFMessageComposeViewController()
controller.body = self.textView.text
controller.recipients = [self.phoneField.text!]
controller.messageComposeDelegate = self
self.presentViewController(controller, animated: true, completion: nil)
}
else
{
print("Error")
}
}
extension MyViewController : MFMessageComposeViewControllerDelegate
{
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult)
{
controller.dismissViewControllerAnimated(true, completion: nil)}
}
}
Any Suggestions how can i send it to multiple recipients?
If user is entering multiple phone numbers in your textfield then you need to prompt the user to separate phone numbers using comma (or any other symbol) through which you can separate the string and add it into your array, then pass that array in controller.recipients
here is an example
if (MFMessageComposeViewController.canSendText())
{
let controller = MFMessageComposeViewController()
controller.body = self.textView.text
let phoneNumberString = "123456789,987654321,2233445566"
let recipientsArray = phoneNumberString.components(separatedBy: ",")
controller.recipients = recipientsArray
controller.messageComposeDelegate = self
self.presentViewController(controller, animated: true, completion: nil)
}
else
{
print("Error")
}
If you want to add multiple recipients then you can write this...
here is my code...
if (MFMessageComposeViewController.canSendText())
{
let composeVC = MFMessageComposeViewController()
composeVC.messageComposeDelegate = self
// Configure the fields of the interface.
composeVC.recipients = ["4085551212","8597485365","2564756984"]
composeVC.body = "Hello from California!"
// Present the view controller modally.
self.presentViewController(composeVC, animated: true, completion: nil)
}
func messageComposeViewController(controller: MFMessageComposeViewController,
didFinishWithResult result: MessageComposeResult)
{
// Check the result or perform other tasks.
// Dismiss the message compose view controller.
controller.dismissViewControllerAnimated(true, completion: nil)
}
Ok, im a bit further now. I got the email button working within the app, but it doesnt add the picture that i have selected in UIImageview in the e-mail. Can someone tell me how to add the picture selected to the email body?
#IBAction func FotoKnop(sender: AnyObject) {
}
#IBAction func chooseImageFromPhotoLibrary() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
}
#IBAction func chooseFromCamera() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
// start e-mail
#IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["jvanhattem#it-serve.nl"])
mailComposerVC.setSubject("Mail vanuit PicMail")
mailComposerVC.setMessageBody("Onderstaand de doorgestuurde informatie", 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)
}
}
You should have a look at documentation for MFMailComposeViewController
You can set the recepients and attachment using setToRecipients: and addAttachmentData:mimeType:fileName:
Try this code fur your email function:
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["nurdin#gmail.com"])
mailComposerVC.setSubject("Sending you an in-app e-mail...")
mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)
return mailComposerVC
}
And this code in your function for the action or where you want to add...
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
// On Success
} else {
// Error handling here
}