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
}
Related
Im trying to learn how to access and use the camera on IOS devices, trufully i cant find all that much info on it, at least not thats up to date or useful to learn at a beginner level.
Regardless, I've tried the below code but nothing happens when I click the button to open the camera it just freezes and does nothing, am i missing something or have i done something wrong?
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var myImg: UIImageView!
var newMedia: Bool!
#IBAction func cameraRoll(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
self.dismiss(animated: true, completion: nil)
if mediaType.isEqual(to: kUTTypeImage as String){
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
myImg.image = image
if (newMedia == true) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(ViewController.image(image:didFinishsavingWithError:contextInfo:)), nil)
} else if mediaType.isEqual(to: kUTTypeMovie as String){
//vid support
}
}
}
func image(image: UIImage, didFinishsavingWithError error: NSErrorPointer, contextInfo:UnsafeRawPointer){
if error != nil {
let alert = UIAlertController(title: "Save Failed", message: "Failed to save image", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func takePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
newMedia = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
This is the code:
// Only allow photos to be picked,not taken.
imagePickerController.sourceType = .photoLibrary
this is the error: Type 'UIImagePickerControllerSourceType' has no member 'photoLibrary'
Just trying to complete the official tutorial Start Developing iOS Apps (Swift)
//MARK: Actions
#IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
//Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagepickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked,not taken.
imagePickerController.sourceType = .photoLibrary
//Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, competion: nil)
}
#IBAction func setDefaultLabelText(sender: UIButton) {
mealNameLabel.text = "Default Text"
}
}
Okay, it looks like you are probably usingSwift 2.2 (maybe it's this for Swift 2.3 also). You want this syntax:
imagePickerController.sourceType = .PhotoLibrary
Note the capitalization. Keep in mind, Xcode 8.2 (released 12 December 2016) will be the last version of Xcode to support Swift 2.x. Sometime in 2017 you will probably need to use Swift 3 for new App Store submissions.
EDIT:
Here's my full Swift 2.2 code, followed by my Swift 3.0 code. Please note two things:
I'm also using the Camera app and have checks to make sure it's present - which isn't the case for the simulator.
Your app will crash in iOS 10 unless you add the following to your info.plist file:
NSCameraUsageDescription
Used to capture new image for photo effect
NSPhotoLibraryUsageDescription
Used to select an image for photo effect
You may put different values in the tags.
Swift 2.2:
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
}
extension SelectViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Camera App
func openCameraApp() {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.cameraCaptureMode = .Photo
picker.modalPresentationStyle = .FullScreen
presentViewController(picker,
animated: true,
completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .Alert)
let okAction = UIAlertAction(
title: "OK",
style:.Default,
handler: nil)
alertVC.addAction(okAction)
presentViewController(
alertVC,
animated: true,
completion: nil)
}
// MARK: Photos Albums
func showImagePicker() {
picker.allowsEditing = false
picker.sourceType = .PhotoLibrary
// picker.modalPresentationStyle = .Popover
presentViewController(picker,
animated: true,
completion: nil)
picker.popoverPresentationController?.sourceView = self.view
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
self.performSegueWithIdentifier("ShowEditView", sender: self)
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(false, completion: nil)
}
// MARK: Seque to EditViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowEditView" {
if let vc = segue.destinationViewController as? EditViewController {
vc.image = image
}
}
}
}
Swift 3.0 (only the extension code has syntax changes):
func openCameraApp() {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,
animated: true,
completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
// MARK: Photos Albums
func showImagePicker() {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
// picker.modalPresentationStyle = .Popover
present(picker,
animated: true,
completion: nil)
picker.popoverPresentationController?.sourceView = self.view
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
self.performSegue(withIdentifier: "ShowEditView", sender: self)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: false, completion: nil)
}
// MARK: Seque to EditViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowEditView" {
if let vc = segue.destination as? EditViewController {
vc.image = image
// vc.image = images[0]
}
}
}
Got the following. I made a simple IOS / Swift app that needs to send an image to a specific e-mail. What i already got working:
Take picture
Grap picture from existing photo's
Image is shown in Image View
Send button thats leads me to mail with already configured: recipient, subject and messagebody.
What i need to get working is how i can add the selected image from Image View to be added to the e-mail when i press send.
Following code is the one i use:
FOR TAKING AND SELECTING IMAGES:
#IBOutlet var imageView: UIImageView!
#IBOutlet weak var PicLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#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)
}
For 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)
}
}
Any thoughts would be great!
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)
//Add Image as Attachment
if let image = imageView.image {
let data = UIImageJPEGRepresentation(image, 1.0)
mailComposerVC.addAttachmentData(data!, mimeType: "image/jpg", fileName: "image")
}
return mailComposerVC
}
I have a button in my app which opens up an email to be sent to me, when this button is pressed the email app on iPhone opens up and when sent is pressed the email is sent however the window doesn't close and then return to my app. Also when i press cancel it gives the option to save/delete draft but again doesn't close the window and return to my app. I have attached the email code below.
#IBAction func SendMessage(sender: AnyObject) {
var mail: MFMailComposeViewController!
let toRecipients = ["usalim76#gmail.com"]
let subject = "Enquiry"
let body = "Your body text"
mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(toRecipients)
mail.setSubject(subject)
mail.setMessageBody(body, isHTML: true)
presentViewController(mail, animated: true, completion: nil)
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
looks like you forgot to implement the MFMailComposeViewControllerDelegate, add this:
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
Managed to fix it!
#IBAction func SendMessage(sender: AnyObject) {
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(["someone#somewhere.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
}
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)
}
}
I would like to be able to view a list of both photos and videos stored on the user's iPhone so I can allow them to select the file for upload. So far, I have it working where photos show up in the list, but no videos are showing up. The code I'm using to display the photos library is the following:
#IBAction func btnAddPicOrVideo(sender: AnyObject) {
let pickerC = UIImagePickerController()
pickerC.delegate = self
self.presentViewController(pickerC, animated: true, completion: nil)
}
As I mentioned, I'm able to display a list of photos and select one of them just fine. The problem is that I'm unable to see or select any videos. Is there a way to specify for both pictures and videos to be displayed? Or, do I have to display pictures and videos separately?
I'm currently running my code on the simulator and I have a video file stored on it locally.
Thanks in advance.
I was able to get this resolved by specifying
import MobileCoreServices
and I changed the code I specified above as such:
#IBAction func btnAddPicOrVideo(sender: AnyObject) {
let pickerC = UIImagePickerController()
pickerC.mediaTypes = [kUTTypeImage as NSString, kUTTypeMovie as NSString]
pickerC.delegate = self
self.presentViewController(pickerC, animated: true, completion: nil)
}
class ScoutDetailPage: UIViewController,UIImagePickerControllerDelegate {
var picker:UIImagePickerController? = UIImagePickerController()
let imageView = UIImageView ()
{
override func viewDidLoad(){
// Do any additional setup after loading the view.
self.loadOrTakePhotos()
}
func loadOrTakePhotos()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker!.sourceType = UIImagePickerControllerSourceType.Camera
picker?.delegate = self
self .presentViewController(picker!, animated: true, completion: nil)
}
}
else if (pickersegment.selectedSegmentIndex == 1)
{
picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
picker?.delegate = self
self.presentViewController(picker!, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let pickedimage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = pickedimage
if (imageView.image != nil)
{
print("image not empty")
// Do something here.
picker .dismissViewControllerAnimated(false, completion: nil)
}
else
{
print("IMAGE VIEW NIL")
}
}
func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) {
if error != nil {
let alert = UIAlertController(title: "Save Failed",
message: "Failed to save image",
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true,
completion: nil)
}
}
}