Pin Annotation with UIAlertView - ios

I created a button in a "bottom bar." When the user presses the button, I am trying to show a UIAlertView, so the user can enter an address which will result in a blue pin being shown on the map. This pin should then be saved to NSUserDefaults, so that the location is saved each time the app is restarted.
Here is what I have so far. The user can enter the address in the UIAlertView, but nothing happens...
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Select Headquarters"
message:#"Enter Address"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[alert show];
UITextField *field = [alert textFieldAtIndex:0];
field.placeholder = #"Enter HQ Address";
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *hqAddress = [NSString stringWithFormat:#"%#", field.text];
[self.geocoder geocodeAddressString:hqAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D hqCoordinate = location.coordinate;
NSLog (#"%f %f", hqCoordinate.latitude, hqCoordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = hqCoordinate;
MKPointAnnotation *hqAnnotation = [[MKPointAnnotation alloc] init];
[hqAnnotation setCoordinate:hqCoordinate];
[hqAnnotation setTitle:#"HQ"];
[[self mapView] addAnnotation:hqAnnotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
}
}];
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:HQ_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

You should implement the UIAlertViewDelegate and put your action code for alert button selection in to the delegate method.
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Select Headquarters"
message:#"Enter Address"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
[alert show];
[alert release] // if non-arc project.
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
// add your code here for tagging the map
// saving to nsuserdefaults.
}

Related

Getting user location not working?

I am new to the MapView topic.Now I am working on the map view.I am getting the san Francisco location longitude and latitude values.I am testing in the simulator.It is not showing the current location longitude and latitude values.
With the help of this tutorial http://www.creativeworkline.com/2014/12/core-location-manager-ios-8-fetching-location-background/ I am developing the app.
In AppDelegate file I wrote the following code like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIAlertView * alert;
//We have to make sure that the Background App Refresh is enable for the Location updates to work in the background.
if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied){
alert = [[UIAlertView alloc]initWithTitle:#""
message:#"The app doesn't work without the Background App Refresh enabled. To turn it on, go to Settings > General > Background App Refresh"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
}else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted){
alert = [[UIAlertView alloc]initWithTitle:#""
message:#"The functions of this app are limited because the Background App Refresh is disable."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alert show];
} else{
self.locationTracker = [[LocationTracker alloc]init];
[self.locationTracker startLocationTracking];
//Send the best location to server every 60 seconds
//You may adjust the time interval depends on the need of your app.
NSTimeInterval time = 60.0;
self.locationUpdateTimer =
[NSTimer scheduledTimerWithTimeInterval:time
target:self
selector:#selector(updateLocation)
userInfo:nil
repeats:YES];
}
return YES;
}
I have imported Location Tracker class in my ViewController
and I wrote the following code to get the location name and addresss
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
__block NSString *returnAddress = nil;
[geoCoder reverseGeocodeLocation:self.appDelgate.locationTracker.myLastLocation_ completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks lastObject];
if (placemark)
{
returnAddress = [NSString stringWithFormat:#"%# %#",placemark.subLocality,placemark.subAdministrativeArea];
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:#"address"];
}
}];
Now my problem is that it is not going inside block.So that I am getting the "returnAddress" as (null).
I wrote like this even though it is not coming
- (void)updateLocationToServer {
NSLog(#"updateLocationToServer");
// Find the best location from the array based on accuracy
NSMutableDictionary * myBestLocation = [[NSMutableDictionary alloc]init];
for(int i=0;i<self.shareModel.myLocationArray.count;i++){
NSMutableDictionary * currentLocation = [self.shareModel.myLocationArray objectAtIndex:i];
if(i==0)
myBestLocation = currentLocation;
else{
if([[currentLocation objectForKey:ACCURACY]floatValue]<=[[myBestLocation objectForKey:ACCURACY]floatValue]){
myBestLocation = currentLocation;
}
}
}
NSLog(#"My Best location:%#",myBestLocation);
NSLog(#"latitude %#",[myBestLocation valueForKey:#"latitude"]);
NSLog(#"longitude %#",[myBestLocation valueForKey:#"longitude"]);
self.DICT=[NSDictionary dictionaryWithDictionary:myBestLocation];
//If the array is 0, get the last location
//Sometimes due to network issue or unknown reason, you could not get the location during that period, the best you can do is sending the last known location to the server
if(self.shareModel.myLocationArray.count==0)
{
NSLog(#"Unable to get location, use the last known location");
self.myLocation=self.myLastLocation;
self.myLocationAccuracy=self.myLastLocationAccuracy;
}else{
CLLocationCoordinate2D theBestLocation;
theBestLocation.latitude =[[myBestLocation objectForKey:LATITUDE]floatValue];
theBestLocation.longitude =[[myBestLocation objectForKey:LONGITUDE]floatValue];
self.myLocation=theBestLocation;
self.myLocationAccuracy =[[myBestLocation objectForKey:ACCURACY]floatValue];
}
NSLog(#"Send to Server: Latitude(%f) Longitude(%f) Accuracy(%f)",self.myLocation.latitude, self.myLocation.longitude,self.myLocationAccuracy);
//TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server
//After sending the location to the server successful, remember to clear the current array with the following code. It is to make sure that you clear up old location in the array and add the new locations from locationManager
[self.shareModel.myLocationArray removeAllObjects];
self.shareModel.myLocationArray = nil;
self.shareModel.myLocationArray = [[NSMutableArray alloc]init];
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
__block NSString *returnAddress = nil;
self.locationActual = [[CLLocation alloc]initWithLatitude:[[myBestLocation objectForKey:LATITUDE]floatValue] longitude:[[myBestLocation objectForKey:LONGITUDE]floatValue]];
//CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
// __block NSString *returnAddress = nil;
CLLocation *locloc = [[CLLocation alloc] initWithLatitude:[[myBestLocation objectForKey:LATITUDE]floatValue] longitude:[[myBestLocation objectForKey:LONGITUDE]floatValue]];
[geoCoder reverseGeocodeLocation:locloc completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks lastObject];
if (placemark)
{
returnAddress = [NSString stringWithFormat:#"%# %#",placemark.subLocality,placemark.subAdministrativeArea];
//[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:#"address"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"" message:returnAddress delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}];
}
What mistake i have done here.
Can anyone please help to clear this confusion.
Thanks in Advance.
Are you sure you are using the return address after completion block? I have used the above code and its working fine.
Here you can download the sample code
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
__block NSString *returnAddress = nil;
CLLocation *locloc = [[CLLocation alloc] initWithLatitude:12.92243 longitude:80.23893];
[geoCoder reverseGeocodeLocation:locloc completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks lastObject];
if (placemark)
{
returnAddress = [NSString stringWithFormat:#"%# %#",placemark.subLocality,placemark.subAdministrativeArea];
//[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:returnAddress] forKey:#"address"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"" message:returnAddress delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}];
//If you try to access retunAddress here you will get nil.
OUTPUT
Go to iOS Simulator -> Debug -> Location -> Custom location... And enter your long/lat coordinates.
In the simulator there is no way to get the actual GPS based data so you need to simulate is with your lat-long which you can set by going
Debug -> Location -> Custom Location
and set your values there.
Probably you are simulating the location in the simulator. In your xCode's console panel there is an arrow button. Click that button and select "Don't simulate location". For reference, see the image.
If that doesn't resolve the problem then run the application. Go into the Debug menu of the simulator and choose the "Custom location" option as shown in the image.

Saving app data after iphone/ipad reset

The photo in the link below illustrates the app I am currently working on, the name is a UITextfield that the user edits him/herself and the balance is label in which the user clicks the add button to add their desired funds. Then the two textfields below that allow for the input of money spent and how it was spent, this is then saved as a UITableviewCell in the UITable view. The problem I am currently having right now is when I restart my iPhone device the previously inputted data is rested meaning the user will have to rewrite everything which wouldn't help as this is an app to monitor one's savings. I did some googling to see if there was a fix for this I came across NSUserDefaults and tried the following code in my viewDidLoad.
Could someone provide the steps for a different approach to keep the inputted information where it is even after the user turns off his or her iPhone/iPad etc. Heres the photo link
http://imgur.com/DceJ7gs
[[NSUserDefaults standardUserDefaults] synchronize];
This is the code I am using to add funds which in turn changes the balance displayed by the uilabel Balance in the above photo
- (IBAction)addFunds:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Add Funds" message:#"Please add your funds" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[_inputStatement resignFirstResponder];
[_spent resignFirstResponder];
[myTableView resignFirstResponder];
[_custName2 resignFirstResponder];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//alertview input text was blank so we are doing a check
if([[alertView textFieldAtIndex:0].text isEqual:#""] && buttonIndex == 1){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Input Required" message:#"Please fill in the textfield" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else {
if(buttonIndex == 1){
NSString *tempText = [alertView textFieldAtIndex:0].text;
float toAdd = [tempText floatValue];
float add = [_currentBalance.text floatValue];
if(toAdd < 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"You can't add a negative number, try again" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
} else {
add = add + toAdd;
if(add >= 99999999.50){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Well you broke it" message:#"You are not allowed to input this much. In the event you do have these funds, I apologize for putting in this restriction. Personally contact me at thejobemuhammed#gmail.com for further inquiries." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else {
_currentBalance.text = [NSString stringWithFormat:#"%.2f", add];
if(!array){
array = [[NSMutableArray alloc]init];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
date1 = [NSDate dateWithTimeIntervalSinceNow:5];
NSString *resultString = [dateFormatter stringFromDate:date1];
[array insertObject:[NSString stringWithFormat:#"%#%#%#",#"$",tempText, #" deposited"] atIndex:0];
[date insertObject:resultString atIndex:0];
[details insertObject:#"This is a deposit" atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
}
[_inputStatement resignFirstResponder];
[_spent resignFirstResponder];
[myTableView resignFirstResponder];
}
add this code where you want to save . i am not getting where are you saving .
save it using this code
NSString *valueToSave = #"hereis yourvalue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"preferencekyename"];
[[NSUserDefaults standardUserDefaults] synchronize];
to get it back later using this code
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferencekyename"];

Multiple UIAlertViews to Enter Data

I have two buttons that will pop up an alertview with textfield to input data. However, only certain characters are allowed in each of the two textfields. Somehow, if I press the second button, the character set from the first button is used. What's going on here?
Also, what would be a more elegant form of inputting data without having to use an alertview? Could I use a modal view? If so, how?
- (IBAction)editRate
{
if(!self.powerOn) return;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Rate"
message:#"Enter New Daily Rate"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter New Rate";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
if ([field.text rangeOfCharacterFromSet:set].location != NSNotFound)
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert show];
FeeRate.text=#"0.00";
}
else
{
FeeRate.text = field.text;
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:RATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
- (IBAction)editDate
{
if(!self.powerOn) return;
UIAlertView *alertDate = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Date"
message:#"Enter New Date"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alertDate.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alertDate textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alertDate show];
}
- (void)alertDate:(UIAlertView *)alertDate clickedButtonAtIndex:(NSInteger)buttonIndex2
{
if (buttonIndex2 != alertDate.cancelButtonIndex)
{
UITextField *fieldDate = [alertDate textFieldAtIndex:0];
fieldDate.placeholder = #"Enter New Date";
NSCharacterSet * setnew = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789/"] invertedSet];
if ([fieldDate.text rangeOfCharacterFromSet:setnew].location != NSNotFound)
{
UIAlertView *errorAlert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers and slashes are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert1 show];
FeeDate.text=#"00/00/0000";
}
else
{
FeeDate.text = fieldDate.text;
[[NSUserDefaults standardUserDefaults] setObject:fieldDate.text forKey:DATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
When a UIAlertView is dismissed then a function called
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
is called.
So, both your alert views call this function.
One way to tell which alertView is calling it, you could create an ivar or better two properties like this:
#property (nonatomic, strong) UIAlertView *rateAlert;
#property (nonatomic, strong) UIAlertView *dateAlert;
and you should initialize like this:
[self setRateAlert:[[UIAlertView alloc] initWithTitle...
[self.rateAlert show];
and
[self setDateAlert:[[UIAlertView alloc] initWithTitle...
[self.dateAlert show];
and then:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView==self.rateAlert) {
//do whatever for rateAlert
} else {
//do whatever with dateAlert
}
}

UIAlertView keeps re-appearing after dismissWithClickedButtonIndex included in performSelector: withObject: afterDelay:

I have a button which I want to implement with password before triggering a segue if the password is correct. it all looks fine up to the moment when you type in wrong password and I have implemented another alertView to tell the user the password is wrong. When the alert view pops out and dismisses after some delay, it keeps re-appearing and disappearing and nothing else can be done on the screen!
How to stop the re appearing?
Below is my part of the code that deals with this:
- (IBAction)editLeagues:(id)sender {
[self presentAlertViewForPassword];
}
-(void)presentAlertViewForPassword
{
_passwordAlert = [[UIAlertView alloc]initWithTitle:#"Password"
message:#"Enter Password to edit Leagues"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[_passwordAlert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
_passwordField = [_passwordAlert textFieldAtIndex:0];
_passwordField.delegate = self;
_passwordField.autocapitalizationType = UITextAutocapitalizationTypeWords;
_passwordField.tag = textFieldPassword;
[_passwordAlert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSString *password = [NSString stringWithFormat:#"55555"];
if ( ![_passwordField.text isEqual:password]) {
_wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[_wrongPassword show];
[self performSelector:#selector(allertViewDelayedDissmiss:) withObject:nil afterDelay:2];
}
else
{
[self performSegueWithIdentifier:#"addLeague" sender:[alertView buttonTitleAtIndex:0]];
}
}
-(void) allertViewDelayedDissmiss:(UIAlertView *)alertView
{
[_wrongPassword dismissWithClickedButtonIndex:-1 animated:YES];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] >= 4 )
{
return YES;
}
else
{
return NO;
}
}
[_wrongPassword dismissWithClickedButtonIndex:-1 animated:YES]; will call the delegate method alertView:didDismissWithButtonIndex:
You have two options:
don't set a delegate on the wrong password alert
check for the correct alert in alertView:didDismissWithButtonIndex: e.g.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alert == _passwordAlert) {
NSString *password = [NSString stringWithFormat:#"55555"];
// and so on
}
}
Issue is causing because when you dismiss the wrong password alert it'll also call the didDismissWithButtonIndex delegate method.
Solution 1
Set the delegate of wrong password alert to nil.
wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
Solution 2
Add a tag to your alertView. And change your methods like:
-(void)presentAlertViewForPassword
{
_passwordAlert = [[UIAlertView alloc]initWithTitle:#"Password"
message:#"Enter Password to edit Leagues"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[_passwordAlert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
passwordAlert.tag = 7;
_passwordField = [_passwordAlert textFieldAtIndex:0];
_passwordField.delegate = self;
_passwordField.autocapitalizationType = UITextAutocapitalizationTypeWords;
_passwordField.tag = textFieldPassword;
[_passwordAlert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 7)
{
NSString *password = [NSString stringWithFormat:#"55555"];
if ( ![_passwordField.text isEqual:password])
{
_wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[_wrongPassword show];
[self performSelector:#selector(allertViewDelayedDissmiss:) withObject:nil afterDelay:2];
}
else
{
[self performSegueWithIdentifier:#"addLeague" sender:[alertView buttonTitleAtIndex:0]];
}
}
}

Uialertview text to NSMutableArray, ios 4.3

i have been trying to copy text input from alertview textfield to a NSMutableArray that i will use later, alertview pops up and i enter the input to text field but when i press OK alert view disappears but doesnt copy text to my mutable array
here is my code
-(IBAction)add:(UIButton *)sender
{
addCustomStand = [[NSMutableArray alloc] init];
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Enter a Stand Location"
message:#" "
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
UITextField *nameField = [[UITextField alloc]
initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
nameField.text = #"";
[dialog addSubview:nameField];
if ([nameField text]){
NSLog(#"Name Field %# ",nameField.text);
[addCustomStand addObject:nameField.text];
}
[nameField release];
[dialog show];
[dialog release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
NSLog(#"Button 1 was selected.");
NSLog(#"StandLocations %# ",addCustomStand);
}
}
here is my output on log screen
2012-02-07 20:26:57.315 Avicii[1399:b603] Name Field
2012-02-07 20:26:59.720 Avicii[1399:b603] Button 1 was selected.
2012-02-07 20:26:59.721 Avicii[1399:b603] StandLocations (
""
)
anyone can help whats wrong with that code?
That's because [nameField text] doesn't have user entered value yet when you added it in your [addCustomStand addObject:nameField.text];
so change your adding into array in UIAlertView delegate method.
-(IBAction)add:(UIButton *)sender
{
addCustomStand = [[NSMutableArray alloc] init];
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Enter a Stand Location"
message:#" "
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
UITextField *nameField = [[UITextField alloc]
initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
nameField.text = #"";
// Note at this line
nameField.tag = 100;
//
[dialog addSubview:nameField];
[nameField release];
[dialog show];
[dialog release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
// Note at this line
UITextField* nameField = (UITextField *)[alertView viewWithTag:100];
[addCustomStand addObject:nameField.text];
//
NSLog(#"Button 1 was selected.");
NSLog(#"StandLocations %# ",addCustomStand);
}
}
You are adding nameField.text to your addCustomStand array before you even show the alert dialog. At the time you add it to the array the value is an empty string.
Instead you need to copy the value into your array during your clickedButtonAtIndex: method, by doing something like this:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
NSString *location;
UIView *view;
for (view in [alertView subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
location = [(UITextField*)view text];
}
}
if (location) {
[addCustomStand addObject:location];
}
}
}

Resources