Hi to all of stackoverflow,
i'm Italian so, i'm sorry for my bad English... :D
i tried to create a simple tableView for listing a few names and a number... all with core data.
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Track *track = [[self fetchedResultsController] objectAtIndexPath:indexPath];
if(YES == self.editing) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Modifica nome" message:#"Prego, inserire di seguito il nuovo nome:" delegate:self cancelButtonTitle:#"Annulla" otherButtonTitles:#"Salva", nil];
newname = [[alert addTextFieldWithValue:track.name label:#"Nome"] text];
[alert textField].autocorrectionType = UITextAutocorrectionTypeNo;
[alert show];
[alert release];
[selectedTrack release];
} else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Aggiungi minchiate" message:#"Sei sicuro di voler aggiungere una michiata a" delegate:self cancelButtonTitle:#"Annulla" otherButtonTitles:#"Salva", nil];
newname = [[alert addTextFieldWithValue:track.trackAbstract label:#"Minchiate"] text];
[alert textField].autocorrectionType = UITextAutocorrectionTypeNo;
[alert show];
[alert release];
[selectedTrack release];
}
}
I want to send the value of the textfield to my attributes that i've created first...
Need I put the code in this method?!
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
//HERE?!
}
}
And how i can set a new value on a core data attribute?
ANY help is appreciated... Thanks in advance!
Yes, you would put the code to grab the value from the text field in the alertView:willDismissWithButtonIndex:
method. Assuming you've created a model class for that entity (which I assume you have, as I see a class called Track in your code), you can set the value of an attribute by using dot syntax:
Track.someAttribute = newValue
Or without dot syntax, it would be [Track setSomeAttribute:newValue].
Also, note that UIAlertView's addTextFieldWithValue:label: is an undocumented method, which isn't a problem if this is an app you're planning to create just for yourself, but using it in an app submitted to the App Store will likely get it rejected.
Related
I am already aware of the fact that there is an option for us to send sms programmatically i.e. using MFMessageComposeViewController, but is it possible to schedule the message to the specified recipient. I am currently using the following code to send sms:
Class smsClass = (NSClassFromString(kMessageComposer));
if(smsClass != nil && [MFMessageComposeViewController canSendText])
{
MFMessageComposeViewController *smsSendController = [[[MFMessageComposeViewController alloc] init] autorelease];
smsSendController.messageComposeDelegate = self;
smsSendController.body = messageBodyView.text;
smsSendController.recipients = [[[NSArray alloc]initWithObjects:numberField.text,nil]autorelease];
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 6.0)
{
[self presentViewController:smsSendController animated:YES completion:nil];
}
else
{
[self presentModalViewController:smsSendController animated:YES];
}
}
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
switch (result)
{
case MessageComposeResultCancelled:
{
UIAlertView *smsCancelledAlert = [[UIAlertView alloc] initWithTitle:kApp message:kCancel
delegate:self cancelButtonTitle:kOk otherButtonTitles: nil];
[smsCancelledAlert show];
[smsCancelledAlert release];
}
break;
case MessageComposeResultFailed:
{
UIAlertView *smsFailedAlert = [[UIAlertView alloc] initWithTitle:kApp message:kError
delegate:self cancelButtonTitle:kOk otherButtonTitles: nil];
[smsFailedAlert show];
[smsFailedAlert release];
}
break;
case MessageComposeResultSent:
{
UIAlertView *smsSentAlert = [[UIAlertView alloc]initWithTitle:kApp message:kSent delegate:self cancelButtonTitle:kOk otherButtonTitles:nil, nil];
[smsSentAlert show];
[smsSentAlert release];
}
break;
default:
break;
}
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 6.0)
{
[self dismissViewControllerAnimated:YES completion:nil];
}
else
{
[self dismissModalViewControllerAnimated:YES];
}
}
I also would like to know whether this code works perfect in all versions above 4.3 till date 6.0. As of now I don't have the device available to test this. So would need some answers from some one who experienced this code as working/failed.
In addition to this, I would want to schedule the message i.e. user specified date&time and the process should be running in background without any user interaction.
How to achieve this?
With MFMessageComposerViewController it is not possible to send without user interaction.
you may consider creating a custom webservice to sms gateway to do achieve this
I have iphone app in which i enter any number value like 10 2 0 1 0.2 etc i want that instead of this if user enter any text it should alert that enter a number.
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Value Must Be In Number " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
try this code:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField==txtMobileNo)
{
[self validatePhone];
}else
{
[textField resignFirstResponder];
}
// called when 'return' key pressed. return NO to ignore.
return YES;
}
- (BOOL) validatePhone
{
NSString *phoneRegex = #"^+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
if ([phoneTest evaluateWithObject:txtMobileNo.text] == YES)
{
NSLog(#"proper phone nO ");
return YES;
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:#"Please,Enter Your Person proper phone no" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil ];
[alert show];
[alert release];
NSLog(#"phone no. not in proper format");
return NO;
[txtMobileNo becomeFirstResponder];
}
}
I hope you helpful.
That disrupts the app kind of, doesn't it? What you want to look at is the UITextfield delegate methods. Set your viewController as the textields delegate and make it respond o UITextFieldDelegate protocol.
I would implement the textField:shouldChangeCharactersInRange:replacementString method and check the replacementString for unwanted characters.
But rather than displaying an alert, I guess I would just return NO if unwanted characters are contained there. Then, when the user enters something other than what you want, nothing happens.
you can check if it is a number using the following:-
NSString *yourString= #"121212";
NSCharacterSet *decimalNUmSet= [NSCharacterSet decimalDigitCharacterSet];
BOOL isNum= ([[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#""] ||
[[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#"."]);
here the second part includes decimal numbers also.
the other way is to present a numeric keyboard to user so that he can type only numbers.
You validate the entered character and do your logic in this delegate ,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// your logic to restriction goes here.like check the entered char and through alert
}
-(BOOL) validateNumericValue:(NSString*) textValue
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:textValue];
if (number != nil)
{
return YES;
}
return NO;
}
I'm currently working in Xcode on an iOS app...
I've set up a UIAlertView (with a question as the message ) to pop up with a text field to retrieve a response.
The desired functionality is that upon entering an incorrect value into the text field, the UIAlert would loop... Until the correct response is entered. At this point, the UIAlert would be dismissed.
Heres what I have so far...
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString* correctAnswer = #"2";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Alarm"
message:#"1 + 1 ="
delegate:self
cancelButtonTitle: nil
otherButtonTitles:#"Continue", nil ];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField* answerField = [alert textFieldAtIndex:0];
answerField.keyboardType = UIKeyboardTypeNumberPad;
answerField.placeholder = #"answer";
[alert show];
// I feel like this would work, but I know it doesn't...
NSString *answerFieldString = answerField.text;
if ([answerFieldString isEqualToString: correctAnswer ])
{
[alert dismissWithClickedButtonIndex:-1 animated:YES];
}
}
I've done extensive google searching and can't come up with a solution... Any responses would be much appreciated!
try this...
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *answerFieldString = answerField.text;
if ([answerFieldString isEqualToString: correctAnswer ])
{
[alertView dismissWithClickedButtonIndex:-1 animated:YES];
}
}
I have a UISegmentControl that select nothing through IB, after the user selects the segment it becomes selected. How do i do it so that it doesnot gets selected?
//Show question method
-(void)question:(NSInteger)i
{
// Path to the plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Question" ofType:#"plist"];
// Set the plist to an array
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//Check the number of entries in the array
NSInteger numCount = [array count];
if(i <numCount)
{ NSDictionary *dict = [array objectAtIndex:i];//load array index 0 dictionary data
self.title = [NSString stringWithFormat:#"Question %d", i+1];//set the nav bar title
quest.text = [dict valueForKey:#"Question"];//Set the Question to storage
ans.text = [dict valueForKey:#"Answer"];//Set the Answer to storage
NSInteger option = [[dict valueForKey:#"NumberOfOption"] integerValue ];//Check options to determine the question type
//check if the option is is a QRCode or Multiple Choices Question
if (option ==0)
{
QRbutton.alpha = 1; //show the QR Code Button If there is no options
OptionsAnswer.alpha = 0;//Hide Option if there is no options
}
else
{
QRbutton.alpha = 0.0;//Hide QR Code Button if there is options
OptionsAnswer.alpha = 1;//Show Option if there is options
[OptionsAnswer setTitle:[dict valueForKey:#"Option1"] forSegmentAtIndex:0];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option2"] forSegmentAtIndex:1];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option3"] forSegmentAtIndex:2];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option4"] forSegmentAtIndex:3];//Set Option Answer Value
[OptionsAnswer addTarget:self action:#selector(OptionAnswerCheck) forControlEvents:UIControlEventValueChanged];//Call action when options is being selected
}
}
else {
//if question is all answered, it will prompt an alert for end game video.
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Well Done"
message:#"You Have Answered All The Questions, Oh Wait A Minute I Heard A Cracking Sound...." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}
//Check if the selected Option is correct
-(IBAction)OptionAnswerCheck
{
//define a persistant location to save which question has been answered
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];//question storages
//pass the value from the selected option to a string
//NSString * selectedTitle = ([OptionsAnswer selectedSegmentIndex] >= 0) ? [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]] :
NSString * selectedTitle = [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]];
NSLog(#"Selected Title = %#",selectedTitle);//test
//check if the selected value is equal to the answers
if ([selectedTitle compare:self.ans.text] ==NSOrderedSame)
{
//Popup to say answer Correct
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Correct!"
message:#"Nice Work, Lets Move On To The Next Question" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
//increase the question number
[self question:++currentQuestion];
//save increased question
[userDefaults setInteger:currentQuestion forKey:#"currentQuestion"];
}
else
{
//Popup to say answer Wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Incorrect"
message:#"Close! But That's Not Right, Try Another Answer" delegate:nil
cancelButtonTitle:#"Try Again." otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
//OptionsAnswer.selectedSegmentIndex = UISegmentedControlNoSegment;
}
Just search for setMomentary: in your developer documentation inside Xcode.
I'm not entirely sure what you're asking here, but I think that you want to set the momentary property toYES.
The property is in the inspector of IB as well. (Can't post a screenshot, I'm on my iPhone).
I'm sick of writing basic UIAlertView's, ie:
UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc
Instead of doing this, is it possible to put all this in a "helper" function, where I can return the buttonIndex, or whatever an alert usually returns?
For a simple helper function I guess you could feed parameters for the title, message, I'm not sure whether you can pass delegates in a parameter though, or bundle info.
In pseudo-code, it could be like this:
someValueOrObject = Print_Alert(Title="", Message="", Delegate="", Bundle="") // etc
Any help on this would be great.
Thanks
In 4.0+ you can simplify the alert code using blocks, a bit like this:
CCAlertView *alert = [[CCAlertView alloc]
initWithTitle:#"Test Alert"
message:#"See if the thing works."];
[alert addButtonWithTitle:#"Foo" block:^{ NSLog(#"Foo"); }];
[alert addButtonWithTitle:#"Bar" block:^{ NSLog(#"Bar"); }];
[alert addButtonWithTitle:#"Cancel" block:NULL];
[alert show];
See Lambda Alert on GitHub.
This is what I wrote, when I got sick of doing the same:
-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName {
[self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: nil];
}
-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName informing:(id)delegate {
[self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: delegate];
}
-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName withExtraButtons:(NSArray *)otherButtonTitles informing:(id)delegate {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: title
message: message
delegate: delegate
cancelButtonTitle: firstButtonName
otherButtonTitles: nil];
if (otherButtonTitles != nil) {
for (int i = 0; i < [otherButtonTitles count]; i++) {
[alert addButtonWithTitle: (NSString *)[otherButtonTitles objectAtIndex: i]];
}
}
[alert show];
[alert release];
}
You can't write a function that will display an alert and then return a value like a buttonIndex though, because that value-returning only occurs when the user presses a button and your delegate does something.
In other words, the process of asking a question with the UIAlertView is an asynchronous one.