Trying to attach image to mail in my app - ios

I'm using the UIimagepicker to choose an image that should be attached to a mail in my ios app. I'm getting this error:
Warning: Attempt to present < MFMailComposeViewController: 0xc142ab0 > on < ViewControllerMail: 0xb642520 > while a presentation is in progress!
I'm new to this so.. i gues i'm dismissing the views wrong? I don't even know if the code works to attach the choosen image.
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToUse = editedImage;
} else {
imageToUse = originalImage;
[self dismissViewControllerAnimated:YES completion:NULL];
}
MFMailComposeViewController * mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
// make sure you can make NSData from the object
[mailComposer addAttachmentData:UIImageJPEGRepresentation(imageToUse, 1.0) mimeType:#"image/jpg" fileName:#"what ever you want to call the file"];
[self presentViewController:mailComposer animated:YES completion:nil];
}
}
Thank you!

The problem is that your are presenting the mail composer while the image picker is being dismissed. Make use of the completion parameter:
[self dismissViewControllerAnimated:YES completion:^{
MFMailComposeViewController * mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
// make sure you can make NSData from the object
[mailComposer addAttachmentData:UIImageJPEGRepresentation(imageToUse, 1.0) mimeType:#"image/jpg" fileName:#"what ever you want to call the file"];
[self presentViewController:mailComposer animated:YES completion:nil];
}];

Related

uploaded photo in ui image viewer keep disappears

I can upload a photo into ui image viewer from camera roll but when I restart my app or go to another page and come back, the uploaded photo disappears. How do I keep them?
- (IBAction)selectImage:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
UIImage *chosenImage = selectedImage;
self.homeImage.image = chosenImage;
[self.view setNeedsDisplay];
[picker dismissViewControllerAnimated:YES completion:NULL];
NSData *imageData = UIImagePNGRepresentation(chosenImage.images);
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];
}
I expect the second method to keep the image in the internal database and keep showing my uploaded image, but it doesn't.
You need to load the image from file and assign it to your view after view is created, something similar to:
- (void)viewDidLoad {
NSString * imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];
self.homeImage.image = [UIImage imageWithContentsOfFile:imagePath];
}

Xcode: Add attachment using picker to email

I have developed an app that allows the user to choose a video from the photo gallery and send it as an attachment in an email. I am able to choose a video from the gallery and proceed with sending the email but the video does not get attached with the email. There are no errors in the console.
ViewController.h:
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MessageUI/MessageUI.h>
#interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate,MFMailComposeViewControllerDelegate>
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)choose:(id)sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIAlertController *myAlertController = [UIAlertController alertControllerWithTitle:#"MyTitle"
message: #"MyMessage"
preferredStyle:UIAlertControllerStyleAlert ];
[self presentViewController:myAlertController animated:YES completion:nil];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)choose:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self performSelector:#selector(email:) withObject:chosenImage afterDelay:0.5];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)email:(UIImage *)choosenImage{
NSString *iOSVersion = [[UIDevice currentDevice] systemVersion];
NSString *model = [[UIDevice currentDevice] model];
NSString *version = #"1.0";
NSString *build = #"100";
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setToRecipients:[NSArray arrayWithObjects: #"support#myappworks.com",nil]];
[mailComposer setSubject:[NSString stringWithFormat: #"MailMe V%# (build %#) Support",version,build]];
NSString *supportText = [NSString stringWithFormat:#"Device: %#\niOS Version:%#\n\n",model,iOSVersion];
supportText = [supportText stringByAppendingString: #"Please describe your problem or question."];
[mailComposer setMessageBody:supportText isHTML:NO];
NSData *data = UIImagePNGRepresentation(choosenImage);
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:#""];
[self presentViewController:mailComposer animated:YES completion:nil];
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any suggestion/help would be much appreciated. Thank you.
You mentioned that you're trying to attach a video, and you've configured your UIImagePickerController to limit the mediaTypes to only videos. The problem then is that you're asking for the "edited image" in the "didFinishPickingMediaWithInfo" method:
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
The user did not pick an image - they picked a video. You need to use this instead:
NSURL *chosenVideoUrl = info[UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:chosenVideoUrl];
You can then pass the videoData to your email method and attach to the email. Be sure to update the mimeType from "image/png" to "video/mp4", as well.
If u need to attach both video and image you have write to code for both,but you written only for attaching an image.You can try the code below for getting both
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqual:(NSString *)kUTTypeMovie]) {
NSString *videoURL = info[UIImagePickerControllerMediaURL];
[self emailImage:nil orVideo:videoURL];
}else {
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
[self emailImage:chosenImage orVideo:nil];
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
UIImagePickerControllerMediaURL will return file url unlike UIImagePickerControllerEditedImage ,so can use NSData method dataWithContentsOfFile as bellow.
if (choosenImage) {
NSData *data = UIImagePNGRepresentation(choosenImage);
NSString *filename = [NSString stringWithFormat:#"Image_%#.png",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"image/png" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}else {
NSData *data = [NSData dataWithContentsOfFile:videoFile];
NSString *filename = [NSString stringWithFormat:#"Video_%#.mp4",TimeStamp];
[mailComposer addAttachmentData:data mimeType:#"video/mp4" fileName:filename];
[self presentViewController:mailComposer animated:YES completion:nil];
}
it will be good if you give a filename for the attachment it will be help full after it downloading.if you wish you can use a TimeStamp for that.
#define TimeStamp [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000]

Share a picture in chat, base64 issue

I am developing a chat, in chat I need to share pictures, my app has a button to select an image from gallery.
This is my button code:
[upBtn2 addTarget:self action:#selector(uploadImage:) forControlEvents:UIControlEventTouchUpInside];
In gallery the user can select an image to share in chat with someone else, the conversation is just 1 to 1 chat.
This is my code.
- (IBAction)uploadImage:(id)sender
{
if ([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker =
[[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType =
UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [NSArray arrayWithObjects:
(NSString *) kUTTypeImage,
nil];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
newMedia = NO;
}
}
-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
Uploadedimage.image=image;
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
// [self performSelector:#selector(uploadToServer) withObject:nil afterDelay:0.0];
XMPPMessage *message = [[XMPPMessage alloc] initWithType:XMPP_MESSAGE_TYPE_CHAT to:[self.contact jid]];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *imageStr = [GTMBase64 stringByEncodingData:imageData];
//decoding
NSData *imageData2 = [GTMBase64 decodeString:imageStr];
[message addBody:imageStr];
[[[AppDelegate appDelegate] xmppStream] sendElement:message];
XMPPJID *myJID = [[[AppDelegate appDelegate] xmppStream] myJID];
[self addMessage:#{
XMPP_TIMESTAMP: [NSDate date],
XMPP_MESSAGE_USERNAME: [myJID bare],
XMPP_MESSAGE_TEXT: imageStr,
}];
[self.tableView reloadData];
[self scrollToBottom:true];
}
- (void)image:(UIImage *)image
finishedSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
if (error) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: #"Archivo guardado"
message: #"Error al guardar archivo"\
delegate: nil
cancelButtonTitle:#"Aceptar"
otherButtonTitles:nil];
[alert show];
}
}
I am getting an issue, the code it is showing
2014-10-14 11:01:21.973 Ucity[2907:60b] messages: (
{
text = "/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAE9KADAAQAAAABAAAFcAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/..."
I need to see the image there but for some reason its showing that text.
I am using GTMBase 64 library
#import "GTMBase64.h"
Can someone help me to fix this problem?
That cryptic text is the image. It's just the base-64 string representation of the image. I assume you're doing this base-64 encoding for a reason (e.g. this format is required by some service to which you are uploading the image).
I'm presuming from your question that you want to show the image somewhere. I'm just trying to reconcile this with this code, in which you retrieved the image, converted it to a base-64 string, then discarded the original image, and now you're asking us why you're only seeing the string.
If you need the image again, there are a couple of options:
Keep the UIImage (or the NSData) that you grabbed in didFinishPickingMediaWithInfo.
You could alternatively convert the base-64 string back to a NSData (and then create a UIImage from that). This is a pretty convoluted approach, but it would work.
As an aside, if you wanted, you could probably replace GTMBase64.h with the native base-64 methods that Apple exposed in iOS 7. See https://stackoverflow.com/a/19794564/1271826.
Also, I don't personally like grabbing the UIImage and doing the PNG conversion to get the NSData. I always grab the original asset as shown here. This ensures there's no loss of information and that the resulting NSData isn't larger than it needs to be.

How to take video from gallery like image inside application in ios

In my application i need to take video from simulator and i need to upload to server.can any one help to me.Please provide any solution as soon as possible.
Thanks & Regards
T.swathi
First, create a UIImagePickerController
On your class, you will need to implement the UIImagePickerControllerDelegate protocol and wire it up to the delegate property on the picker. You should be able to get the location of the media selected from didFinishPickingMediaWithInfo once the user has selected something.
//Check in iOS Device not in Simulator
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// this is the file system url of the media
NSURL* videoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
// TODO: read in data at videoUrl and write upload it to your server
}
Use this function may be help full
-(void)selectVideoButtonClicked:(id)sender{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:YES completion:nil];
}
and take delege of "UIImagePickerControllerDelegate" & and import framework and using delegate function pick video from library
MobileCoreServices.framework first import in project and after than import in file CoreServices/CoreServices.h
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
// Handle a movie capture
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeMovie, 0)
== kCFCompareEqualTo) {
NSString *moviePath = [[info objectForKey: UIImagePickerControllerMediaURL] path];
NSLog(#" Video Path %#",moviePath);
NSString *fileName = [[NSString alloc]init];
//If you wants get File Name Then you can use this
if ([moviePath rangeOfString:#"//"].location != NSNotFound) {
NSString *separatorString = #"//";
NSArray *disSplit = [moviePath componentsSeparatedByString:separatorString];
fileName = disSplit[1] ;
// [self videoUploadingDirect:moviePath];
}
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Thanks :)

Send mail with image attachment from camera

There are a LOT of tutorials and info about how to send attachment with your iphone / ipad app, but with pre-defined images or other file-type.
But how do i send an mail with a current file from my iphone/ipad. More specific, an image or image from camera?
Cheers and thank you
If you are using UIImagePickerController to capture image than when you capture image :
#import <MobileCoreServices/UTCoreTypes.h> // framework MobileCoreServices.framework
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self sendMailWithImage:image];
}
[picker dismissModalViewControllerAnimated:NO];
}
- (void)sendMailWithImage:(UIImage *)image
{
MFMailComposeViewController * mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
// make sure you can make NSData from the object
[mailComposer addAttachmentData:UIImageJPEGRepresentation(image, 1.0) mimeType:#"image/jpg" fileName:#"what ever you want to call the file"];
[self presentViewController:mailComposer animated:YES completion:nil];
}
MFMailComposeViewController * mailComposer = [[MFMailComposeViewController alloc]init];
mailComposer.mailComposeDelegate = self;
UIImage *myImage = // some code to get your image or what ever file you want
// make sure you can make NSData from the object
[mailComposer addAttachmentData:UIImageJPEGRepresentation(imageToShare, 1.0) mimeType:#"image/jpg" fileName:#"what ever you want to call the file"];
[self presentViewController:mailComposer animated:YES completion:nil];

Resources