MFMailComposeViewController won't open after picking an email from the contact list - objective-c

I'm trying to send an email to a contact on the contact list. I am using a ABPeoplePickerNavigationController. Once the user selects a contact's email, the following happens:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
if(property == kABPersonEmailProperty){
[self dismissModalViewControllerAnimated:YES];
ABMultiValueRef emails = ABRecordCopyValue(person, property);
int index = ABMultiValueGetIndexForIdentifier(emails, identifier);
NSString *emailValueSelected = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, index);
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"the subject"];
[controller setMessageBody:#"Hello there" isHTML:NO];
[controller setToRecipients:[[NSArray alloc] initWithObjects:emailValueSelected, nil]];
if (controller){
[self presentModalViewController:controller animated:YES];
}
return NO;
}
return YES;
}
The emailValueSelected variable has the correct email value, and all the code seems to be executed without any problems (even the body of the if(controller){...} statement).
The issue is that nothing happens, the email controller is never shown. I've tried both with [self presentViewController:controller animated:YES completion:nil] and [self presentModalViewController:controller animated:YES];.
I use the exact same code on another part of my application to send an email and it works correctly, so I'm guessing it has something to do with the people picker.

Are you using a tab bar controller?
Then you should try
[self.tabBarController presentModalViewController:controller animated:YES];
Also you can set a breakpoint and do a po controller to see if the controller is initialized correctly (i.e. it is not nil)

The problem was that the people picker modal being dismissed was colliding with the email modal which was trying to appear. I solved it by making the people picker modal disappear instantly and not animated.
if(property == kABPersonEmailProperty){
[self dismissModalViewControllerAnimated:NO];
//etc...
}

I had success doing:
[peoplePicker presentViewController:picker animated:YES completion:nil];
instead of:
[self presentViewController:picker animated:YES completion:nil];

Related

Calling UIImagePickerControler present in viewdidload Doesn't Work

I want to launch camera when my view controller loads. I tried calling takePhoto method in viewdidload but nothing happens, what did I do wrong? I am getting the following error msg:
"Attempt to present on whose view is not in the window hierarchy!"
When I inspect element UIImagePickerController, it is nil... Interestingly, I can place a button that calls this method and when I tap the button it works fine, but not when I call it in view did load...
- (IBAction)takePhoto {
UIImagePickerController *uiipc=[[UIImagePickerController alloc]init];
uiipc.delegate=self;
uiipc.mediaTypes=#[(NSString *)kUTTypeImage];
uiipc.sourceType=UIImagePickerControllerSourceTypeCamera|UIImagePickerControllerSourceTypePhotoLibrary;
uiipc.allowsEditing=YES;
[self presentViewController:uiipc animated:YES completion:NULL];
}
Try this: Call the camera from the view did appear method:
// makeCameraOff= YES; call this in didFinishPickingMediaWithInfo method
-(void)viewDidAppear:(BOOL)animated{
if (makeCameraOff==NO){
[self performSelector:#selector(takePic) withObject:nil afterDelay:0];
}
}
-(void)takePic{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate =self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:nil];
}

ios: Application tried to present a nil modal view controller on target

I am developing an application,the requirement is to open email composer on a button click of UIAlertView.
message which is in message body of email is copied from UITextView. i am using following code snipt:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0)
{
// opening message composer
}
else
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Test mail"];
[picker setMessageBody:messageBody.text isHTML:YES];
[self presentViewController:picker animated:YES completion:NULL];
}
}
// mail compose delegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[self dismissViewControllerAnimated:YES completion:NULL];
}
but the issue is that i am getting error saying Application tried to present a nil modal view controller on target. how we can open default mail composer in ios 7?
As per Apple, You should check is MFMailComposeViewController are able to send your mail just before sending
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Test mail"];
[picker setMessageBody:messageBody.text isHTML:YES];
[self presentViewController:picker animated:YES completion:NULL];
}
Swift:
if MFMailComposeViewController.canSendMail() else {
// Send mail code
}
Ref : Apple Dev url
Swift 4 version
guard MFMailComposeViewController.canSendMail() else {
print("Mail services are not available")
return
}
sendEmail()
Forgetting Mail account configuration in device settings may also lead to this error. Re check whether a mail account is configured in your device or not.

dismissViewControllerAnimated does not work in iOS 7?

I have a cell presenting a Passcode change view controller when tapped.
else if (indexPath.row == 2) {
//Change passcode
NSString *passcode = [[NSUserDefaults standardUserDefaults] stringForKey:#"passcode"];
PAPasscodeViewController *passcodeViewController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionChange];
passcodeViewController.delegate = self;
passcodeViewController.passcode = passcode;
passcodeViewController.simple = YES;
[self presentViewController:passcodeViewController animated:YES completion:nil];
break;
}
a delegate callback method to dismiss the Passcode change view controller when hit cancel:
- (void)PAPasscodeViewControllerDidCancel:(PAPasscodeViewController *)controller {
[self dismissViewControllerAnimated:YES completion:nil];
// [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
// [self.navigationController popViewControllerAnimated:YES];
}
it does not however dismiss the Passcode change view controller when hit the cancel button even though xcode debug hits the code. I tried [self.presentingViewController dismissViewControllerAnimated:YES completion:nil]; it didn't work either. The presentingViewController property is nil.
It worked perfectly on iOS 6 before. Anyone ran into this problem before? Thanks
Your can try this in PAPasscodeViewController, instead of using the delegate,.
[self removeFromParentViewController];

MFMailComposeViewController : cancel doesn't exit to my app?

I'm trying to send a mail with MFMailComposeViewController. It happens when I click a button on my app. Of course when I click the Cancel button of the mail controller I want to go back to my app view but it doesn't work. What to do ? Here is my code :
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Subject"];
[controller setMessageBody:#"<html>Test</html>" isHTML:YES];
[controller setToRecipients:nil];
if(controller) [self presentModalViewController:controller animated:YES];
Thanks for your advices
Have you implemented this delegate method? It's called after the composer is exited by the user.
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error
{
[self dismissViewControllerAnimated:YES completion:nil];
return;
}

Xcode Unrecognized Selector Error

I've been having a ton of issues with this section of an app that I'm writing, I'm sure people here are getting sick of me so I'm going to try and solve all my questions in this post. I'm working on an app that behaves like a photo gallery, and I'm implementing the option to have the user delete photos from their gallery. To accomplish this, I decided to place an invisible button over each picture. When the user hits an "Edit" button, the hidden delete buttons over each picture become active. I'm using the same IBOutlet over each of the hidden buttons for simplicity, and I've tagged each button appropriately in Interface Builder. When the user taps the button over the picture, an alert view appears asking if they really want to delete it. If they click yes, I call removeObjectAtIndex and delete the image from the UI. But, when I click "Yes" in the alert view, I get an error from Xcode stating:
2012-04-04 11:26:40.484 AppName[608:f803] -[UIButton setImage:]: unrecognized selector sent to instance 0x6a922c0
2012-04-04 11:26:40.485 AppName[608:f803] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton setImage:]: unrecognized selector sent to instance 0x6a922c0'*
I've been trying to figure out what is causing this for a few hours now to no avail. I'm not setting the image of a UIButton anywhere in my code. I did in IB, but I simply set the buttons types to Custom so that they appear invisible. I will post my entire file below, I can't find any issues in my code, so any help is much appreciated! Thanks.
EDIT Here is the current version of the code:
- (IBAction)grabImage {
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
_popover = [[UIPopoverController alloc] initWithContentViewController:imgPicker];
[_popover presentPopoverFromRect:self.imageView.bounds inView:self.imageView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
else {
[self presentModalViewController:imgPicker animated:YES];
}
[self.imgPicker resignFirstResponder];
}
// Sets the image in the UIImageView
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;
self.array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView2.image == nil) {
imageView2.image = img;
NSLog(#"The image is a %#", imageView);
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)]];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView3.image == nil) {
imageView3.image = img;
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)]];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView4.image == nil) {
imageView4.image = img;
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)]];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Photo Gallery", #"Photo Gallery");
self.tabBarItem.image = [UIImage imageNamed:#"42-photos.png"];
}
return self;
}
////start of saving////
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
self.array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)]];
[self.user setObject:self.array forKey:#"images"];
[user synchronize];
}
- (void)viewDidLoad
{
self.user = [NSUserDefaults standardUserDefaults];
NSLog(#"It is %#", self.user);
self.array = [[self.user objectForKey:#"images"]mutableCopy];
imageView.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:0]];
imageView2.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:1]];
imageView3.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:2]];
imageView4.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:3]];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
backToGalleryButton.hidden = YES;
tapToDeleteLabel.hidden = YES;
deleteButton1.hidden = YES;
[super viewDidLoad];
}
///// shows the hidden and invisible "delete" button over each photo.
- (IBAction)editButtonPressed:(id)sender {
grabButton.hidden = YES;
editButton.hidden = YES;
backToGalleryButton.hidden = NO;
tapToDeleteLabel.hidden = NO;
deleteButton1.hidden = NO;
}
////
// This is when the user taps on the image to delete it.
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(#"User Clicked Yes. Deleting index %d of %d", alertView.tag, [array count]);
NSLog(#"The tag is %i", alertView.tag);
[self.array removeObjectAtIndex: alertView.tag];
NSLog(#"After deleting item, array count = %d", [array count]);
NSLog(#"Returned view is :%#, in view: %#", [self.view viewWithTag:alertView.tag], self.view);
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}
[self.user setObject:self.array forKey:#"images"];
}
Update: I added breakpoints, and discovered that ((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil; is the line that is causing the crash, I still can't figure out why though.
I don't see setImage: being called in any of that code you pasted into your question, but I can tell you this: UIButton's setImage method actually requires a button state as a second parameter.
e.g.
[UIButton setImage: forState:]
I've linked Apple's documentation for you.
If your calls to setImage: don't have a second parameter, that would explain the "unrecognized selector error" you're seeing.
This is an extension to #MichaelDautermann , who makes a very good point that a UIButton has a setImage:forState: method, but no setImage method. However, you ARE calling set image. Not on a button, but when you say imageView.image and imageView2.image. This invokes the setter method for the image view. I would set a breakpoint (or use NSLog and the %# item) to ensure that imageView is in fact an imageView and not a button. If it somehow changed from under you, this could be causing the issue. Simply set a break point at those two lines and see if you even make it past them.
Additionally, if Xcode isn't popping you over to which line is actually causing the issue, check your crash logs. Symbolicated, the log will give you the line number. Or, a less direct approach would be to set breakpoints at the ends of the methods you provided in your answer, and see how many you get past. Once you crash, you can narrow down which method is causing you grief, and then start setting break points within the method until you get to the line in question.
UPDATE:
You said in the comments that ((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil is what you have, but self.view is a UIControl. Changing the cast won't affect the result. Is the UIImageView whose image you are trying to delete a subview of a UIControl? If not, you're never going to get the image view back from viewWithTag. Generally, self.view refers to a view controller's view, so if you're getting a UIControl, my assumption is either your whole view is a UIControl, or you're doing this in the wrong class. Which class are you doing this in, and what is it a subclass of? It appears you are doing this in a view controller, but I just want to be sure. And again, in either case (UIControl or UIImageView), neither class responds to setImage.