create calling button in iPhone?
I want to create 2 button.when the buttons is pushed,it should make a phone call. ı wrote this code and it works but my problem is the buttons call same number.ı want to call different numbers. can anyone fix my code ?
#define firstnumber @"1"
#define secondnumber @"2"
- (IBAction)first:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:firstnumber message:@"do you want to call?" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alert show];
[alert release];
}
- (IBAction)second:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:secondnumber message:@"do you want to call?" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
// the user cticlicked one of the OK/Cancel buttons
if (buttonIndex == 1)
{
NSLog(@"ok");
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel://%@", firstnumber]];
[[UIApplication sharedApplica开发者_高级运维tion] openURL:url];
[url release];
}
else
{
NSLog(@"cancel");
}
}
`
This should do it:
#define firstnumber @"1"
#define secondnumber @"2"
- (IBAction)first:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:firstnumber message:@"do you want to call?" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
alert.tag = 1;
[alert show];
[alert release];
}
- (IBAction)second:(id)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:secondnumber message:@"do you want to call?" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
alert.tag = 2;
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
// the user cticlicked one of the OK/Cancel buttons
if (buttonIndex == 1)
{
NSLog(@"ok");
NSURL *url;
switch (actionSheet.tag) {
default:
case 1:
url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel://%@", firstnumber]];
break;
case 2:
url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel://%@", secondnumber]];
break;
}
[[UIApplication sharedApplication] openURL:url];
[url release];
}
else
{
NSLog(@"cancel");
}
}
You are always using firstNumber to make phone call. To distinguish between the buttons and alert views, you can set tag to alert view. According to the tag of the alertview, u can make call to first or second.
Your numbers are hardcoded as shown below:
#define firstnumber @"1"
#define secondnumber @"2"
You can read the number by adding a UITextField and reading its value in your alert view.
- Create a uitextview in your view
- Write the delegate methods and create a iboutlet in your controller
- In your alert view callback read the value entered in the uitextfield and use it to create your url
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"tel://%@", textField.text]];
精彩评论