My iOS app starts off with a pop-up message (UIAlertView) where you have to enter text in a UITextField. I would like the default value of the UITextField to be equal to the user's previous input.
Example: at 1pm, the user types "Happy" and clicks OK. When he re-opens the app at 2pm, the Text Field already has "Happy" as default value, he just needs to click OK. At 3pm, he opens the app, the default value is "Happy" but he changes it to "Angry", and then clicks OK. At 4pm, "Angry" is the default value when he opens the app.
- (void)viewDidLoad
{
[super viewDidLoad];
//Pop-up TextField
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you feeling ?" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * machineTextFieldInit = [alert textFieldAtIndex:0];
machineTextFieldInit.placeholder = #"Mood";
[alert show];
}
Many thanks in advance for your help and advice !
It appears what you're looking for is a method to persist a user's data across multiple app sessions. This can be done a number of different ways:
Core Data
User Defaults
Plist File
External Server
Since the code you've supplied looks rather simple, perhaps using the NSUserDefaults will be the way to go.
To store a value in NSUserDefaults use this bit of code when the user presses the button:
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
UITextField * machineTextField = [alertView textFieldAtIndex:0];
NSString * input = machineTextField.text;
if (input != nil)
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:input forKey:#"my.app.domain.machineTextField"];
[defaults synchronize];
}
}
And when you present the dialog, load the value from the defaults.
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString * previous = [defaults objectForKey:#"my.app.domain.machineTextField"];
//Pop-up TextField
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you feeling ?" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * machineTextFieldInit = [alert textFieldAtIndex:0];
machineTextFieldInit.placeholder = previous ? previous : #"Mood";
[alert show];
}
The simplest answer I can think of is the store the previous value in a class property, then when the user clicks cancel, store the value into their property
#property NSString *previousValue;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == [alertView cancelButtonIndex]){
previousText = machineTextFieldInit.text;
}
}
Then on the init of your alertview test field set
machineTextFiledInit.text = previousValue;
Haven't tested and there may be an easier way :)
Also don't forget to set previousValue to a default value for when the user clicks the first time.
Edit: If you want it to store it passed the close of the app
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
[coder encodeObject:previousValue forKey:#"previousVal"];
}
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
previousValue = [coder decodeObjectForKey#"previousVal"];
}
Related
In my application I send data to server and parse.
But I have to send image and you need to choose category.
When you don't choose category I show for user information.
But: how can I check if the user has filled in all the fields? In my app choose image and category?
This is my code with show error when you don't choose category and send action:
- (IBAction)submitItem:(UIButton *)sender {
if ([category isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Category 'All' is reserved" message:#"You need to choose different category" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return;
}
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
///// send image to server
NSString *urlString = urlSaveFullImageToServer;
Your change could be as simple as using an else statement...
- (IBAction)submitItem:(UIButton *)sender {
if ([category isEqualToString:#""]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Category 'All' is reserved" message:#"You need to choose different category" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return;
}
else {
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
///// send image to server
NSString *urlString = urlSaveFullImageToServer;
...
Personally I think a better approach is not to enable the "send" button until all of the data is complete.
Set the submit button enabled property to NO and then when the various pieces of information are entered (the image, the category) check to see if everything is complete - once it is, set enabled to YES
This question already has answers here:
Taking Text From a UIAlertView
(4 answers)
Closed 8 years ago.
UIAlertView *alertViewChangeName=[[UIAlertView alloc]initWithTitle:#"Change Name" message:#"What is your teacher's name?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
alertViewChangeName.alertViewStyle=UIAlertViewStylePlainTextInput;
[alertViewChangeName show];
I am just looking to retrieve the input from the textbox and place it within a UILabel or an NSString to later use and/or manipulate.
You will need to invoke UIAlertView's delegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString *test = [[alertView textFieldAtIndex:0] text];
}
You just need to use the -textFieldAtIndex: method on UIAlertView to get your Textfield. e.g:
UIAlertView *alert = ...
UITextField *textInput = [alert textFieldAtIndex:0];
textInput.text = ...
// get user input
NSString *userInput = textInput.text;
So I'm building a notes app saving the notes to a NSUSerDefaults after the click of a button. Well when I load that view and add the note and click on the button to save it the first time, it works properly. However if I don't leave the view and add a new message and try to click the button to save it, my app crashes. which I really don't understand why. The xcode version I'm using right now doesn't give me a lot of details on my errors, but I do see this
0x00015a9b <+1175> xor %eax,%eax
Program received signal 'SIGABRT'
This is the code of the IBAction that is triggered after the button click (sent event)
-(IBAction)saveNote{
NSUserDefaults *prefs=[NSUserDefaults standardUserDefaults];
//If empty add text to synthesized array and then add the array to the USer defaults
if([[prefs stringArrayForKey:#"Subjects"] count]==0){
NSLog(#"Went through here");
[notesSubject addObject:writeNote.text];
[prefs setObject:notesSubject forKey:#"Subjects"];
NSLog(#"The length of the array is %d",[notesSubject count]);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Note Saved" message:#"Your note was saved" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
//[notesView.tableView reloadData];
}
//If not empty, get the array stored in the user defaults and set it to a temp array, add text to that temp array and then place the temp array back to the user defaults.
else{
newSubjects=[[NSMutableArray alloc]init];
beforeSubjects=[[NSArray alloc]init];
newSubjects= [prefs stringArrayForKey:#"Subjects"];
[newSubjects addObject:writeNote.text];
[prefs setObject:newSubjects forKey:#"Subjects"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Note Saved" message:#"Your note was saved" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
//[notesView.tableView reloadData];
}
}
Yeah, I don't really understand why the app crashes on second click.
You're overwriting the mutable newSubjects instance with an immutable instance with this line:
newSubjects= [prefs stringArrayForKey:#"Subjects"];
Instead, it should be this:
newSubjects = [[prefs stringArrayForKey:#"Subjects"] mutableCopy];
Firstly I have this code which saves my video file in the documents directory:
filePath = [NSString stringWithFormat:#"%#/Documents/%f.mp4", NSHomeDirectory(),[[NSDate date] timeIntervalSince1970]];
Secondly I have a UIAlertView that allows the user to enter the name they want for the video they are saving:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"GIVE YOURE VIDEO A NAME" delegate:self cancelButtonTitle:#"Done" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
And I have this to display what is entered:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
if (alertView.alertViewStyle == UIAlertViewStylePlainTextInput){
NSLog(#"Entered: %#",[[alertView textFieldAtIndex:0] text]);
}
}
else
{
NSLog(#"user pressed Button Indexed 1");
// Any action can be performed here
}
}
Know that I want to do is to save the video file with a name specified by text which was entered in to the UIAlertView. To do this I need to change this line: filePath = [NSString stringWithFormat:#"%#/Documents/%f.mp4", NSHomeDirectory(),[[NSDate date] timeIntervalSince1970]]; which saves the file as the current date and time to the entered text. However, I do not know how I would go about doing that.
Are you asking how to replace the date with the text entered ?
You only need to pass in the string, which you are already doing with the homeDirectory, like so
filePath = [NSString stringWithFormat:#"%#/Documents/%#.mp4", NSHomeDirectory(),[[alertView textFieldAtIndex:0] text]];
I have a calculator that multiplies a value with a certain $ rate. The user can edit the $ rate, and the value is multiplied with the user-entered rate. Here is my code for this:
- (IBAction)edit
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Edit New Amount"
message:#"Enter new 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];
rate.text=#"";
}
else
{
rate.text = field.text;
}
}
else
{
//Cancel
}
}
However, when the app closes and is restarted, the old rate is displayed, not the new user-entered rate. How can I save the new user-entered rate, so that it is retained within the app, even when it is restarted?
If you want the value to be retained after app is closed, then you got to store it somewhere in file system. Easiest and convenient way is to use NSUserDefaults:
//Storing in user defaults
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:RATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
//Retrieving (possibly in app start or viewdidload)
self.rate.text = [[NSUserDefaults standardUserDefaults] objectForKey:RATE_KEY];
One note on usage of NSUserDefaults is that it doesn't support storing every object type, it supports NSString,NSArray,NSNumber etc and primitive types. Since you used NSStrings in your code I assumed you can save it as string to defaults.
Have you tried creating a new variable to hold the new input as the user enters the new input, and then setting whatever the new input is to that new variable? It sounds like it is restarting from the last variable that was set in the input.