Adding more than one confirmationalerts (UIAlertView) - iphone

Basically, what I try to do is to add multiple confirmationalerts...but I just cant get it to work. No matter what confirmationalert i press, the "Continue" button leads to the exact same thing (a body without text and a subject with "XXXX")...
Any idea how to make the confimationalerts to lead to different things?
EDIT 2; No matter what button I press (continue or dismiss), the app sends the user to mail.app...
-(IBAction)mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
[mail setTitle:#"Open mail"];
[mail setMessage:#"....."];
[mail setDelegate:self];
[mail addButtonWithTitle:#"Continue"];
[mail addButtonWithTitle:#"Dismiss"];
[mail show];
[mail release];
}
-(IBAction)feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_TIPSA_TAG];
[feedback setTitle:#"Open mail"];
[feedback setMessage:#"....."];
[feedback setDelegate:self];
[feedback addButtonWithTitle:#"Continue"];
[feedback addButtonWithTitle:#"dismiss"];
[feedback show];
[feedback release];
}
- (void)showConfirmAlert
{
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if([alertView tag] == ALERTVIEW_FEEDBACK_TAG) {
NSURL *url = [[NSURL alloc] initWithString:#"mailto:?subject=XXXX"];
[[UIApplication sharedApplication] openURL:url];
[url release];
}
else if (buttonIndex == 1) {
}
else if ([alertView tag] == ALERTVIEW_MAIL_TAG) {
NSString *subject = #"YYYY";
NSString *body = #".....";
NSString *path = [NSString stringWithFormat:#"mailto:?subject=%#&body=%#", subject, body];
NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
}
else if (buttonIndex == 1) {
}
}

You'll need to set a tag on your UIAlertView objects and switch on them in your delegate method, this is why the delegate method takes in the UIAlertView, so you can do stuff based on which object the button was pressed.
#define ALERTVIEW_MAIL_TAG 100
#define ALERTVIEW_FEEDBACK_TAG 101
- (IBAction) feedback {
UIAlertView *feedback = [[UIAlertView alloc] init];
[feedback setTag:ALERTVIEW_FEEDBACK_TAG];
//...
}
- (IBAction) mail {
UIAlertView *mail = [[UIAlertView alloc] init];
[mail setTag:ALERTVIEW_MAIL_TAG];
}
-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger) buttonIndex {
if([alertView tag] == ALERTVIEW_MAIL_TAG) {
//do stuff...
} else {
//do other stuff...
}
}

The delegate method is specified by the UIAlertViewDelegate protocol, you can't change that.
There are 2 things you can do:
Use 2 different delegates and specify a clickedButtonAtIndex-method for each class.
In the clickedButtonAtIndex-method first check which alertview has sended the message. This requires to tag the UIAlertView (see answer by Jacob Relkin) or to create an instance variable for each UIAlertView.

You should specify which of your buttons is the cancel button, and then you need to check which button was clicked and don't do anything if it was the cancel button. I.e., when you create the alert:
alertView.cancelButtonIndex = 1;
And when you get the button clicked message:
if (buttonIndex == alertView.cancelButtonIndex) return;

Related

UIAlertView doesn't work

I have an alert view with the two buttons, but the buttons don't open the urls. I don't know the error. Help please.
Here's the code:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Mapes"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"http://maps.apple.com/?q=Plaça+del+Rei+43003+Tarragona";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
if([title isEqualToString:#"Google Maps"])
{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = #"comgooglemaps://?daddr=Plaça+del+Rei+43003+Tarragona&directionsmode=walking";
NSURL *ourURL = [NSURL URLWithString:ourPath];
[ourApplication openURL:ourURL];
}
}
I think the special character (ç) in the address is throwing the NSURL off. Try using the stringByAddingPercentEscapesUsingEncoding: method of NSString to encode it before passing it to the NSURL initializer.
Please check the URL which we fired.
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
As I check with both URL, they are not able to open.
You can check the URL with above code whether URL is able to open or not.
You have to check the URL's, try this:
-(IBAction)showAlertView {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Obrir en..."
message:#"Es pot requirir la aplicació de Google Maps"
delegate:self
cancelButtonTitle:#"Millor no..."
otherButtonTitles:#"Mapes",#"Google Maps",nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//0 is cancel
if(buttonIndex == 1)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!q=Pla%C3%A7a+del+Rei+43003+Tarragona&data=!1m4!1m3!1d4618!2d1.2582895!3d41.1168719!4m11!1m10!4m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1!17b1"];
}
if(buttonIndex == 2)
{
[self openURLWithString:#"https://www.google.com/maps/preview#!data=!1m4!1m3!1d18473!2d1.258181!3d41.1168316!4m13!3m12!1m0!1m1!1sPla%C3%A7a+del+Rei+43003+Tarragona!3m8!1m3!1d26081603!2d-95.677068!3d37.0625!3m2!1i1024!2i768!4f13.1&fid=0"];
}
}
- (void)openURLWithString:(NSString *)string{
UIApplication *ourApplication = [UIApplication sharedApplication];
NSString *ourPath = string;
NSURL *ourURL = [NSURL URLWithString:ourPath];
if([ourApplication canOpenURL:ourURL])
[ourApplication openURL:ourURL];
else
NSLog(#"URL is not valid.");
}
First, you should use elseif in your second condition, because you only want to fire the second if the first isn't true. Second, it seems to be the URL you're using in #"Mapes"... I tested this and that URL seems to be the culprit. When I changed that URL to another test URL, it worked.

Three else-if statements [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Hi I am trying to have 4 buttons and each of them have different alerts when pressed. I am running into an issue, I had 3 buttons and I decided to add a "Rate My App" Button but now it isnt' working, please help me. (By the way the error is Expexted Exspression)(Org.=Organization (Fixed in App), Email- Real email in app,
#define TAG_Band 1
#define TAG_DEV 2
#define TAG_EDEV 3
#define TAG_RATE 4
#interface Org.ContactInfo () <MFMailComposeViewControllerDelegate>
#end
#implementation Org.ContactInfo:UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Contacts";
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)ContactBand:(id)sender;{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact the Band" message:#"Contact the Org. or go to their website!" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Visit the Org. Website",#"E-Mail The Org. President", #"E-Mail The Org. Treasurer", nil];
alert.tag = TAG_Band;
[alert show];
}
-(IBAction)ContactDev:(id)sender;{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact Me" message:#"Contact Me on Features you would like me to consider! I will do my Best to look at all of the Suggestions!" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Visit My Website",#"E-Mail Me!", nil];
alert.tag = TAG_DEV;
[alert show];
}
-(IBAction)RateMyApp:(id)sender;{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Rate My App" message:#"When Your Reviewing my App, Please remember that this app was at no cost to the Mighty Mustang Band." delegate:self cancelButtonTitle:#"Not Right Now" otherButtonTitles:#"Rate My App!!", nil];
alert.tag = TAG_RATE;
[alert show];
}
-(IBAction)AppInfo:(id)sender;{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Version 1.0" message:#"More Updates Coming Soon. Please Feel Free to E-Mail me on features that you would like me to consider" delegate:self cancelButtonTitle:#"Not Right Now" otherButtonTitles:#"Email-Me", nil];
alert.tag = TAG_EDEV;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (alertView.tag == TAG_Band){
if (buttonIndex==1){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://URL.org"]];
}
else if (buttonIndex==2){
//Subject
NSString *emailTitle = #"";
//Recipients
NSString *emailBody=#"Org. President";
NSArray *toRecipients = [NSArray arrayWithObject:#"Person#Org.org"];
MFMailComposeViewController *mc=[[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setSubject:emailBody];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
}
else if (buttonIndex==3){
//Subject
NSString *emailTitle = #"";
//Recipients
NSString *emailBody=#"Org. Treasurer, ";
NSArray *toRecipients = [NSArray arrayWithObject:#"Person#Org.org"];
MFMailComposeViewController *mc=[[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setSubject:emailBody];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
}
}
else if (alertView.tag == TAG_DEV){
if (buttonIndex==1){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://stepheniosdeveloper.wordpress.com"]];
}
else if (buttonIndex==2){
NSString *emailTitle = #"";
//Recipients
NSString *emailBody=#"";
NSArray *toRecipients = [NSArray arrayWithObject:#"Email#gmail.com"];
MFMailComposeViewController *mc=[[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setSubject:emailBody];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
}
}
else if (alertView.tag == TAG_EDEV);{
if (buttonIndex==1){
NSString *emailTitle = #"";
//Recipients
NSString *emailBody=#"";
NSArray *toRecipients = [NSArray arrayWithObject:#"Email#gmail.com"];
MFMailComposeViewController *mc=[[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setSubject:emailBody];
[mc setToRecipients:toRecipients];
[self presentViewController:mc animated:YES completion:NULL];
}
}
else if (alertView.tag == TAG_RATE);{ //Expected Expression
if (buttonIndex==1){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"https://itunes.apple.com/us/app/Org/id607257427?ls=1&mt=8"]];
}
}
}
It worked Before I added the last on (TAG_RATE) but now I don't understand why it isn't working anymore. Please Help.
There is a typo in your code: you have extra ; after the last two else if conditions:
else if (alertView.tag == TAG_EDEV)/*;*/{ // extra `;`
//...
}
else if (alertView.tag == TAG_RATE)/*;*/{ // extra `;` //Expected Expression
// ...
}

Showing an UIAlertView causes EXC_BAD_ACCESS [duplicate]

This question already has answers here:
UIAlertView fails to show and results in “EXC_BAD_ACCESS” error
(6 answers)
Closed 8 years ago.
I'm using AFNetworking to make a web request. After the web request completes. I want a UIAlertView to be shown. I'm using ARC and the code seems to work on devices. If I use a simulator I get an error: EXC_BAD_ACCESS
What am I doing wrong?
UIAlertView* postSubmitAlertView = [[UIAlertView alloc] init];
postSubmitAlertView.delegate = self;
[postSubmitAlertView addButtonWithTitle:#"Ok"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[op setCompletionBlock:^(void) {
if(op.response.statusCode == 200) {
postSubmitAlertView.title = #"Submission Good";
postSubmitAlertView.message = #"GOOD";
} else {
postSubmitAlertView.title = #"Submission Failed.";
postSubmitAlertView.message = #"FAIL";
}
[postSubmitAlertView show];
}];
[op start];
The key problem is that UIKit stuff should be called on the main thread.
Note: For the most part, UIKit classes should be used only from an application’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application’s user interface in any way.
UIKit Framework Reference
Looking at the docs for NSOperation under setCompletionBlock:
Discussion
The exact execution context for your completion block is not guaranteed but is typically a secondary thread. Therefore, you should not use this block to do any work that requires a very specific execution context. Instead, you should shunt that work to your application’s main thread or to the specific thread that is capable of doing it.
The simplest solution to modify your code is to call the UIKit stuff on the main thread
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *URL = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[op setCompletionBlock:^(void) {
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* postSubmitAlertView = [[UIAlertView alloc] init];
postSubmitAlertView.delegate = self;
[postSubmitAlertView addButtonWithTitle:#"Ok"];
if(op.response.statusCode == 200) {
postSubmitAlertView.title = #"Submission Good";
postSubmitAlertView.message = #"GOOD";
} else {
postSubmitAlertView.title = #"Submission Failed.";
postSubmitAlertView.message = #"FAIL";
}
[postSubmitAlertView show];
});
}];
[op start];
}
The EXC_BAD_ACCESS is caused by accessing a released object. To avoid this make your call to UIAlertView kind of modal:
//Function body:
-(void)checkSaving
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Do you want to add these results to your database?"
message:#"\n\n"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Save", nil];
alert.alertViewStyle = UIAlertViewStyleDefault;
[alert show];
//this prevent the ARC to clean up :
NSRunLoop *rl = [NSRunLoop currentRunLoop];
NSDate *d;
d = (NSDate*)[d init];
while ([alert isVisible]) {
[rl runUntilDate:d];
}
}
//Your choice result:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 1)//Save
{
//do something
}
if (buttonIndex == 0)//NO
{
//do something
}
}
//Register the functions in the interface declaration:
#interface yourViewController ()
-(void)checkSaving
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//...
#end
//To call:
[self checkSaving];
I wish this will help you.
UIAlertView* postSubmitAlertView = [[UIAlertView alloc] init];
postSubmitAlertView.delegate = self;
[postSubmitAlertView addButtonWithTitle:#"Ok"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success: %#", operation.responseString);
postSubmitAlertView.title = #"Submission Good";
postSubmitAlertView.message = #"GOOD";
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
postSubmitAlertView.title = #"Submission Failed.";
postSubmitAlertView.message = #"FAIL";
}
];
[postSubmitAlertView show];
Hope this will solve your problem.

How can I access iPod Library in my iPhone app

How access iPod Library in my iPhone app, like to the user listem music when is playing... like in the gameloft games, or the slide show from the Photos.app ?
Look at MPMusicPlayerController. I read it can access the iPod library. I never used it, and I don't know if it can help you...
- (void)addMusicBtnAction{
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAnyAudio];
mediaPicker.delegate = self;
//mediaPicker.prompt = #"Select Audio";
mediaPicker.prompt = NSLocalizedString (#"Select any song from the list", #"Prompt to user to choose some songs to play");
for (UIWindow* window in [UIApplication sharedApplication].windows) {
NSArray* subviews = window.subviews;
if ([subviews count] > 0)
for (UIAlertView *alrt in subviews) {
if ([alrt isKindOfClass:[UIAlertView class]]){
if (alrt.tag == 10020) {
[alrt dismissWithClickedButtonIndex:0 animated:YES];
}
}
}
}
[self presentModalViewController:mediaPicker animated:YES];
//[mediaPicker release];
}
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
NSArray * SelectedSong = [mediaItemCollection items];
if([SelectedSong count]>0){
MPMediaItem * SongItem = [SelectedSong objectAtIndex:0];
NSURL *SongURL = [SongItem valueForProperty: MPMediaItemPropertyAssetURL];
NSString *str = [NSString stringWithFormat:#"%#",SongURL];
appDelegate.musicFilePath = str;
//NSLog(#"Audio Loaded");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your audio has been selected" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil, nil];
alert.tag = 78787878;
[alert show];
// [alert release];
}
[self dismissModalViewControllerAnimated: YES];
}
// Responds to the user tapping done having chosen no music.
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
[self dismissModalViewControllerAnimated: YES];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated:YES];
}

iphone app exit with "No SIM card installed"

I use the MFMessageComposeViewController for sending in App sms. in iPhone 4.0, if there is no SIM card, the app exits. it just gives a pop up message "no sim card installed".
The delegate callback MessageComposeResultSent. But application exits. Is there any way to prevent it from exiting? or how to check if there is any SIM card in the phone?
Code snippets below:
/* Open the system sms service, copying the sms text in system clipboard. */
- (void) sendSMSAsURLRequest {
NSString *phoneNumber = friend.phoneMobile;
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
NSString *textUTIType = (NSString *)kUTTypeUTF8PlainText; // add MobileCoreServices.framework for this type.
[pasteBoard setValue:[self buildSMSText] forPasteboardType:textUTIType];
NSString *urlString = [NSString stringWithFormat:#"sms:%#", phoneNumber];
NSURL *url = [[NSURL alloc] initWithString: urlString];
[[UIApplication sharedApplication] openURL: url];
[url release];
}
-(void) sendInAppSMS {
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
controller.delegate = self;
if([MFMessageComposeViewController canSendText])
{
NSString *smsText = [self buildSMSText];
controller.body = smsText;
controller.recipients = [NSArray arrayWithObjects:friend.phoneMobile, nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result) {
case MessageComposeResultCancelled:
NSLog(#"Cancelled");
break;
case MessageComposeResultFailed:{
NSString *alertString = NSLocalizedString(#"Unknown Error. Failed to send message", #"");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:alertString delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
break;
}
case MessageComposeResultSent:
NSLog(#"SMS sent");
break;
default:
break;
}
[self dismissModalViewControllerAnimated:YES];
}
To Detect Sim Card is installed or not use following Code :
#import CoreTelephony;
CTTelephonyNetworkInfo *networkInfo = [CTTelephonyNetworkInfo new];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (!carrier.isoCountryCode) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No SIM Card Installed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else{
//Paste Your code here
}
The work around I am using now is, a flag in the app delegate,
- (void)applicationWillResignActive:(UIApplication *)aNotification {
if (shouldExitApp) {
exit(0);
}
}
In the SMS sending view controller,
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = NO;
And set the flag again, when in the SMS sending view controller,
- (void) viewDidAppear:(BOOL)animated {
((LuupAppDelegate *)[[UIApplication sharedApplication] delegate]).shouldExitApp = YES;
[super viewDidAppear:animated];
}