Can't set recipients of MFMessageComposeViewController? - iphone

I have a method like this:
void sendSMS{
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.recipients = [NSArray arrayWithObject:#"0933660805"];
[picker setBody:#"Message body"];
picker.messageComposeDelegate = self;
[self.navigationController presentModalViewController:picker animated:YES];
//[picker release];
return;
}
}
Message composer open but recipients and message body are empty (image below). Anybody know how can i fix it :(

Go for this ones and then check may be it will resolve your issue
void sendSMS
{
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
NSString *bodyString = nil;
NSMutableArray *toRecipients = [[NSMutableArray alloc]init];
[toRecipients addObject:#"0933660805"];
[picker setRecipients:(NSArray *)toRecipients];
[toRecipients release];
bodyString = [NSString stringWithFormat: #"Message body"];
[picker setBody:bodyString];
[self presentModalViewController:picker animated:YES];
[picker release];
}
Also take a look at this tutorial http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/
Good Luck!

OK I answered my own question. Now I want no one else to have to go thru this. I was calling this method from just an NSObject. It was a delegate to MFMessageComposeViewControllerDelegate but that made no difference. I had to move this method to my MainViewController, then it worked.

iOS 10.0 is here and this is still a problem for me. So, I have fashioned a workaround.
According to previous comments that initializing the MFMessageComposeViewController in the viewDidLoad() won't solve the problem (which I can attest to), unless the view controller gets presented, it won't be cached. So, the hack here is to make a window, set its root view controller, present a dummy MFMessageComposeViewController instance and immediately dismiss it, somewhere before your actual need (like in viewDidLoad())
Here is a sample code I'm using (Swift 3.0 - Let me know if you were interested in Obj-C counterpart):
let window = UIWindow()
let vc = UIViewController()
window.rootViewController = vc
let messageCompose = MFMessageComposeViewController()
vc.present(messageCompose, animated: false) { [weak messageCompose] in
messageCompose?.dismiss(animated: false, completion: nil)
}
The thing here is that if you present it in the currently active window's view controller chain, it will mess up your UI by showing and hiding the keyboard abruptly (no matter how you try to hide the controller's view and what not), due to the message body selection on present. But adding it to a whole new window which is not in view cycle, it will be correctly initialized and there will be no trace of such transaction on view. Plus, you won't boggle the memory too much this way (because the scope of the controller should be minimal now) and you can initialize your actual MFMessageComposeViewController any time you want and get it much faster now. If your application heavily relies on MFMessageComposeViewController (which I doubt) you can move this to your AppDelegate to be ready anywhere around your app's life cycle.
Cheers,
M.

Try this
- (void)sendSMS
{
if ([MFMessageComposeViewController canSendText]) {
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
NSString *bodyString = nil;
NSArray *toRecipients = [NSArray arrayWithObject:#"NUMBER HERE"];
[picker setRecipients:toRecipients];
[self presentModalViewController:picker animated:YES];
[picker release];
}

In my case (on iPhone 3g s) the problem was when I called [self.navigationController pushViewController... ], when i tried call [self presentModalViewController ...] it worked, I dont know why, but it is. Try it.

set the MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
before if ([MFMessageComposeViewController canSendText]) {...}
Try this.

Try this.
- (void)forwardPromo
{
MFMessageComposeViewController *composeViewController = [[MFMessageComposeViewController alloc] init];
composeViewController.body = #"Message body";
composeViewController.recipients = [NSArray arrayWithObject:#"0933660805"];
composeViewController.messageComposeDelegate = self;
[self presentViewController:composeViewController animated:YES completion:nil];
}

You should have a "nil" at the end of the array:
composeViewController.recipients = [NSArray arrayWithObject:#"0933660805", nil];

Related

Ios MFMailComposeViewController not displaing

I trying to write rhodes native extension extension for opening iOS MailComposer.
Now code "works", but MFMailComposeViewController not displaying and xcode shows warning:
Attempt to present <MFMailComposeViewController: 0x12b60840> on <Iosmailto: 0xc1898d0> whose view is not in the window hierarchy!
I read that UIViewControllers must be in hierarchy, but i can't provide this from Rhodes ruby code or clear-C extension wrapper.
Now i'm trying to present my UIViewController with MFMailComposeController from [UIApplication sharedApplication].keyWindow.rootViewController but mail composer not show yet.
interface from iosmailto.h:
#interface Iosmailto : UIViewController<MFMailComposeViewControllerDelegate>
{
}
#property(nonatomic, assign) id delegate;
//-(IBAction)send_mail:(id)sender;
#end
implementation from iosmailto.m:
#implementation Iosmailto
- (void)viewDidLoad {
[super viewDidLoad];
[self send_mail];
}
- (void)send_mail {
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
composer.mailComposeDelegate = self;
[composer setSubject:[NSString stringWithUTF8String:subj]];
NSArray *recipients_array = [NSArray arrayWithObject:[NSString stringWithUTF8String:recipients]];
[composer setToRecipients:recipients_array];
NSString *composerBody = [NSString stringWithUTF8String:message];
[composer setMessageBody:composerBody isHTML:NO];
[composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentModalViewController:composer animated:YES];
[composer release];
} else {
NSLog(#"Device is unable to send email in its current state.");
}
}
/* some unnecessary for this question methods */
#end
And C function defined in iosmailto.m thats called from Rhodes:
// find root vc
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
// find topmost vc
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
iosmailer = [[Iosmailto alloc] init];
iosmailer.delegate = topController;
[topController presentViewController:iosmailer animated:YES completion:nil];
This app is not for AppStore. Hacks is welcome if needed.
Update init for Iosmailto:
- (id)init
{
self = [super initWithNibName:nil bundle:nil];
return self;
}
Update 2 The short version of this code (without UIViewController wrapper) was my starting point. That's don't work too. And this have the same warning and one more:
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *composer = [[MFMailComposeViewController alloc] init];
composer.mailComposeDelegate = (id<MFMailComposeViewControllerDelegate>)topController ;
[composer setSubject:[NSString stringWithUTF8String:subj]];
NSArray *recipients_array = [NSArray arrayWithObject:[NSString stringWithUTF8String:recipients]];
[composer setToRecipients:recipients_array];
NSString *composerBody = [NSString stringWithUTF8String:message];
[composer setMessageBody:composerBody isHTML:NO];
[composer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[topController presentModalViewController:composer animated:YES];
[composer release];
} else {
}
Use this code to present view controller
[[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:composer
animated:YES
completion:nil];
Ok I think the problem is that your UIViewController doesn't have anything in its view property because you aren't using a .xib file to initialize it. See this question which programmatically creates a UIView and assigns it to the UIViewController's view property. I think that's the right way to go. See the implementation of their -(void)loadView method.
Your use-case is also a little strange, since it looks like your Iosmailto UIViewController doesn't have any content, and you're just using it as a wrapper around MFMailComposeViewController--you might consider reimplementing your C method to directly create a MFMailComposeViewController without the unnecessary layer of indirection of this unnecessary UIViewController that doesn't display anything itself.

Send SMS iPhone

I was trying to send SMS from within my app. I wrote this piece of code but it seems not to work.
No crash, no error log, simply nothing happen (of course I tried to log canSendText and the result is 1).
- (void)viewDidLoad
{
[super viewDidLoad];
messageComposer = [[MFMessageComposeViewController alloc] init];
if ([MFMessageComposeViewController canSendText]) {
[messageComposer setBody:#"Messaggio generato da SMSTest"];
[messageComposer setRecipients:[NSArray arrayWithObject:#"3333333333"]];
[messageComposer setDelegate:self];
[self presentModalViewController:messageComposer animated:YES];
}
}
Can anyone explain me what I'm doing wrong?
The problem is that presentModalViewController does not work in viewDidLoad yet as the view is loaded but might not even be on screen yet. If you put your code in viewWillAppear:animated, this should work.
Edit: As per Saphrosit's comment: viewDidAppear: is an even better place to do this.
I use this successfully:
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
controller.messageComposeDelegate = self;
controller.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:controller animated:YES];
Note that it's messageComposeDelegate, not 'delegate' as you do.
Tim
When i try the code on simulator i get an UIAlert saying text messaging is not available, because simulator canĀ“t send messages. Have you checked that your header file is a delegate of MFMessageComposeViewControllerDelegate ?
YourClassName : UIViewController <MFMessageComposeViewControllerDelegate>
//try this ... it will run ..
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = #"Hello from Kartik";
controller.recipients = [NSArray arrayWithObjects:#"12356478", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}

Sending sms programmatically code Problem

I am writing code to send sms programatically
Program crashes at second last line.
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
picker.messageComposeDelegate = self;
picker.recipients = [NSArray arrayWithObject:#"123456789"]; // your recipient number or self for testing
picker.body = #"test from OS4";
[self presentModalViewController:picker animated:YES];
[picker release];
I assume it's safe to say that it implements
UIViewController <MFMessageComposeViewControllerDelegate>
In which case, I would recommend going back to http://iphonesdkdev.blogspot.com/2010/04/mfmessagecomposeviewcontroller-sample.html, copying their example and progressing from there.

Exception in iPhone app : Modal transition is already in progress

I have what I believe is a fairly simple application at the moment based on a few tutorials cobbled together. I'm using XCode 3.2.3 in OSX 10.6.4. It started as a standard iPhone "Window Based Application". Using interface builder I have added a Tab Bar Controller using the O'Reilly video tutorial here:
http://broadcast.oreilly.com/2009/06/tab-bars-and-navigation-bars-t.html
In the first Tab I have a standard UIView with two buttons. Both call the same function to display a UIImagePickerController:
-(IBAction) btnPhotoClicked:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
if((UIButton *)sender == btnChoosePhoto)
{
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
} else {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
I am running the code inside an emulator so only ever click the button called Choose Photo. When the dialogue is released with a photo chosen this function runs:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *mediaUrl;
mediaUrl = (NSURL *)[info valueForKey:UIImagePickerControllerMediaURL];
if (mediaUrl == nil)
{
imagePuzzle = (UIImage *) [info valueForKey:UIImagePickerControllerEditedImage];
if(imagePuzzle == nil)
{
//--- Original Image was selected ---
imagePuzzle = (UIImage *) [info valueForKey:UIImagePickerControllerOriginalImage];
}
else {
//--- Get the edited image ---
//--- If it was successful the above valueForKey:UIImagePickerControllerEditedImage
//--- would have assigned it already.
}
}
else {
//--- Muppet selected a video
}
// Animate the picker window going away
[picker dismissModalViewControllerAnimated:YES];
ImageViewController *imageViewController = [[ImageViewController alloc] init];
imageViewController.delegate = self;
[self presentModalViewController:imageViewController animated:YES];
[imageViewController release];
}
This is where my problem lies. I've tried many different hacks and iterations but the above code is the simplest to present the problem. When the imageViewController is displayed as a modal dialogue the following exception is thrown:
2010-07-09 15:29:29.667 Golovomka[15183:207] *** Terminating app due to uncaught
exception 'NSInternalInconsistencyException', reason: 'Attempting to begin a modal
transition from <NewViewController: 0x5915f80> to <ImageViewController: 0x594a350>
while a transition is already in progress. Wait for viewDidAppear/viewDidDisappear
to know the current transition has completed'
How do I cure this? I have tried delays and other tricks but do not really understand how I'm supposed to use viewDidAppear or viewDidDisappear to help me. Also of note is that a very basic application with one view loading the picker then displaying another view with the image in does not produce the error. Any help gratefully received.
To address the specific issue described here, you could add the viewDidAppear method in your class:
-(void)viewDidAppear:(BOOL)animated
{
if (/*just visited ImagePicker*/)
{
ImageViewController *imageViewController = [[ImageViewController alloc] init];
imageViewController.delegate = self;
[self presentModalViewController:imageViewController animated:YES];
[imageViewController release];
}
}
Remove those lines from below your call:
[picker dismissModalViewControllerAnimated:YES];
So, whenever your class self appears (is displayed), it will call viewDidAppear... Since this most likely isn't really what you want all the time, you could add some variables to set/clear that defines whether or not to immediately present the imageViewController when self is displayed. Something like "If coming from image picker, show the imageViewController, otherwise do nothing".
That said, imho, pushing modal views is should generally be done in response to a user action and I would maybe rethink the user experience here - e.g. add a subview instead of pushing a modal view which you could do where your currently have the code - but if you're just playing around with some tutorials that should solve the NSInternalInconsistencyException. :) Cheers!
In iOS 5.0 and above you can use
[self dismissViewControllerAnimated:YES completion:^{
//present another modal view controller here
}];
I ran into this issue quite a few times. I recently started using this simple fix:
When I am going to present a new modal view controller immediately after dismissing another modal view controller, I simply dismiss the first one with argument NO in dismissModalViewControllerAnimated:.
Since the second view is presented with an animation, you hardly notice that the first one goes away fast. And you never get the transitions conflict.
I was having the same problem when i wanted to present an MFMailComposeViewController immediately after dismissing the UIImagePickerController. Heres what i did:
I removed the [imagePicker release]; statement from where i was presenting the image picker and put it in didFinishPickingMedia callback.
I used [self performSelector:#selector(presentMailComposer:) withObject:image afterDelay:1.0f];
Here's my code:
Displaying Image Picker
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
NSArray *media = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
if ([media containsObject:(NSString*)kUTTypeImage] == YES) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
[picker setMediaTypes:[NSArray arrayWithObject:(NSString *)kUTTypeImage]];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
[self presentModalViewController:picker animated:YES];
//[picker release];
}
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Unavailable!"
message:#"Could not open the Photo Library."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
Image Picker Delegate Callback - didFinishPickingMedia
NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
UIImage *photoTaken = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//Save Photo to library only if it wasnt already saved i.e. its just been taken
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(photoTaken, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//Pull up MFMailComposeView Controller
[self performSelector:#selector(composeMailWithPhoto:) withObject:photoTaken afterDelay:1.0f];
}
[picker dismissModalViewControllerAnimated:YES];
[picker release];
Display Mail Composer View
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
mailPicker.mailComposeDelegate = self;
// Fill out the email fields and Attach photograph to mail
static NSString *imageType = #"image/jpeg";
NSString *imageName = [NSString stringWithString:#"MyCoffeeCup.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[mailPicker addAttachmentData:imageData mimeType:imageType fileName:imageName];
[mailPicker setToRecipients:[NSArray arrayWithObject:#"hello#xische.com"]];
[self presentModalViewController:mailPicker animated:YES];
//[self.navigationController pushViewController:mailPicker animated:YES];
[mailPicker release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Unavailable!"
message:#"This device cannot send emails."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}

Nothing is editable and no keyboard in MFMailComposeViewController

I'm launching a MFMailComposeViewController like so:
ShareViewController *shareView = [[ShareViewController alloc] initWithSubject:subject body:body footer:footer];
shareView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
shareView.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentModalViewController:shareView animated:YES];
The init looks this:
- (id)initWithSubject:(NSString *)subject body:(NSString *)body footer:(NSString *)footer{
[super init];
self.navigationBar.barStyle = UIBarStyleBlack;
self.mailComposeDelegate = self;
[self setSubject:subject];
body = [NSString stringWithFormat:#"%# %#", body, footer];
[self setMessageBody:body isHTML:YES];
return self;
}
The email window appears, and I can move the cursor around the body of the email. But I am not able to bring up a keyboard, or move the cursor to the To:, CC:, or Subject: fields at all. No idea what's going on. This was previously working but I've recently made several UI changes. 'Cancel' dismisses the modal as expected. 'Send' is not enabled since there's no recipient in the To: field.
Any ideas?
Turns out I had forgotten to call [super viewDidAppear] when I overrode viewDidAppear.