Checking if word is valid in array - iphone

I am using code to check if a word is in my array, if it is I want it to submit it and I have the code for it. If it isn't I want it to pop up a screen. now this all works, the only thing is the screen pops up 2 times, because there are 2 words in my array. here is the code to explain it a little better.
NSArray *searchContacts = [NSArray arrayWithObjects:
#"CADEAU",
#"KADERZ",nil];
NSString *myContact = labelsText.text;
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
this is where I put in my words, CADEAU & KADERZ in this case. When I put one of these words into labelsText.text it does exactly what I want. but for the else statement if the labels text.text word is not CADEAU or KADERZ, it pop ups a screen:
else {
UIAlertView *alert = [[UIAlertView alloc]
This screen will pup up 2 times now, so i'll have to press dismiss 2 times, how would I fix this to just have to press dismiss one time no mather how many words are in the array?

It would be more efficient to use an NSSet, but even if you use an NSArray, you can simply call containsObject: instead of looping through the collection yourself.
if (![searchContacts containsObject:myContact]) {
//show alert...
}

Put a break; after the code showing your alert:
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
// do something
} else {
// show screen
break;
}
}
This will 'break' out of the loop.

I think you want something like this:
BOOL contactFound = NO;
for (NSString *contact in array)
{
if ([contact isEqualToString:myContact])
{
contactFound = YES;
break;
}
}
if (!contactFound)
UIAlertView *alert = [[UIAlertView alloc]...

Use a break after your UIAlertView.
For example:
for (NSString *contact in searchContacts) {
if ([contact isEqualToString:myContact]) {
//do what you want to do
}
else{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert show];
break; //leave for()
}
}
Or use that:
searchContacts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([contact isEqualToString:myContact]) {
//do what you want to do
}
else{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert show];
*stop = YES; //stop enumeration
}
}

Related

Multiple objects in PFQueryTableViewController - Parse.com

I'm trying to display two objects or "classNames" into a PFQueryTableViewController. Here is my code so far with only one object. I can't seem to be able to add more than one object.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
// Customize the table
// The className to query on
self.className = #"Funny";
//self.className = #"Story";
// The key of the PFObject to display in the label of the default cell style
self.textKey = #"title";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 100;
}
return self;
}
Just add more #propertys to your view controller. Make sure to add the necessary ones (className2, textKey2, etc) and to modify the datasource methods of your table view to display the data.
That being said, it seems strange the the view controller is initiated with initWithCoder. That is usually the method invoked by storyboard for views.
I used two object when saving the post. It worked perfectly!
PFObject *quoteNew = [PFObject objectWithClassName:#"New"];
[quoteNew setObject:[[self attribution] text] forKey:#"by"];
[quoteNew setObject:[[self quoteText] text] forKey:#"quoteText"];
[quoteNew setObject:[[self attributionTitle] text] forKey:#"title"];
[quoteNew saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
PFObject *quote = [PFObject objectWithClassName:#"Funny"];
[quote setObject:[[self attribution] text] forKey:#"by"];
[quote setObject:[[self quoteText] text] forKey:#"quoteText"];
[quote setObject:[[self attributionTitle] text] forKey:#"title"];
[quote saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
[self done:self];
} else {
[[[UIAlertView alloc] initWithTitle:#"Uh oh. Somthing went wrong"
message:[[error userInfo] objectForKey:#"error"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles: nil] show];
}
}];
}

Identifying the Push Notification Message

In my project I want to show the events and offers through push notification, but the problem is, I'm able to show the events or offers, not both. Is there any way to identify the message of Push notification. Here's the code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSString *message = nil;
id alert = [userInfo objectForKey:#"alert"];
if ([alert isKindOfClass:[NSString class]]) {
message = alert;
} else if ([alert isKindOfClass:[NSDictionary class]]) {
message = [alert objectForKey:#"body"];
}
if (alert) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Title"
message:#"AThe message." delegate:self
cancelButtonTitle:#"button 1"
otherButtonTitles:#"button", nil];
[alertView show];
}
NSString *contentsInfo = [userInfo objectForKey:#"contTag"];
NSLog(#"Received contents info : %#", contentsInfo);
NSString *nibName = [AppDelegate fetchNibWithViewControllerName:#"EventsViewController"];
EventsViewController *evc = [[EventsViewController alloc] initWithNibName:nibName bundle:nil];
evc.newEvent = YES;
[self.navigationController pushViewController:evc animated:YES];
[UIApplication sharedApplication].applicationIconBadgeNumber = [[[userInfo objectForKey:#"aps"] objectForKey: #"badgecount"] intValue];
}
alert is always an NSDictionary with two keys: body and show-view. The value of the former is the alert message and the latter is a Boolean (false or true). If false, the alert’s View button is not shown. The default is to show the View button which, if the user taps it, launches the application.
check the docs
To identify type of the message you can provide additional fields, as described here
Example:
{
"aps":{
"badge":1,
"alert":"This is my special message!",
"mycustomvar1":"123456",
"mycustomvar2":"some text",
"myspecialtext":"This is the best!",
"url":"http://www.mywebsite.com"
}
}

How to call a variable with a value calculated from one method in another method?

My code does a calculation upon a button press in "IBAction" and returns the result in a string as the "message" in "UIAlertView".
else{
NSString *str = [[NSString alloc] initWithFormat:#"You require an average GPA of at least %.2f to achieve your Goal of %#", gpagoal, (NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Nothing is Impossible"
message:str
delegate:self
cancelButtonTitle:#"Good Luck"
otherButtonTitles:#"Tweet",nil];
//show alert
[alert show];
[alert release];
NSLog(#"All Valid");
}
i have a problem of how to pull the "gpagoal" value from the calculation's "IBAction" method.
below is the code for the standalone button for tweeting, which works if i am able to port over the gpagoal value from the other method.
- (IBAction)sendEasyTweet:(id)sender {
// Set up the built-in twitter composition view controller.
TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
// i have problem trying to pull the result "gpagoal" from the calculation's "IBAction" method as i dunno how to pull out variable from a method to another method.
NSString *str2 = [[NSString alloc] initWithFormat:#"I need an average GPA of at least %.2f this semester to achieve my Goal of %#", gpagoal, (NSString *)[myPickerDelegate.myGoal objectAtIndex: [myPicker selectedRowInComponent:0]]];
// Set the initial tweet text. See the framework for additional properties that can be set.
[tweetViewController setInitialText:str2];
// Create the completion handler block.
[tweetViewController setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
//NSString *output;
switch (result) {
case TWTweetComposeViewControllerResultCancelled:
// The cancel button was tapped.
//output = #"Tweet cancelled.";
NSLog(#"Tweet cancelled");
break;
case TWTweetComposeViewControllerResultDone:
// The tweet was sent.
//output = #"Tweet done.";
NSLog(#"Tweet done");
break;
default:
break;
}
// Dismiss the tweet composition view controller.
[self dismissModalViewControllerAnimated:YES];
}];
// Present the tweet composition view controller modally.
[self presentModalViewController:tweetViewController animated:YES];
}
You simply need a variable that is available throughout your class
// ViewController.h
...
#interface ViewController : UIViewController {
double gpagoal;
}
Make sure it is properly initialized and updated as needed.

For push notifications: how do I add action to alert view to change views?

So I have push notifications sending to my application.
The code that triggers the alert is in my app delegate file (I think thats where it is supposed to go?)
How do I make an action for my alert button so that I can change to a different view?
// Set Below code in your App Delegate Class...
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// Call method to handle received notification
[self apnsPayloadHandling:userInfo];
}
-(void) apnsPayloadHandling:(NSDictionary *)userInfo{
// Example Payload Structure for reference
/*
remote notification: {
acme1 = 11114;
aps = {
alert = {
"action-loc-key" = "ACTION_BUTTON_TITLE";
"loc-args" = ("MSG_TEXT");
"loc-key" = "NOTIFICATION_DETAIL_PAGE";
};
badge = 10;
sound = "chime";
};
}
*/
//======================== Start : Fetching parameters from payload ====================
NSString *action_loc_key;
NSArray *loc_args_array;
int badge;
NSString *sound=#"";
NSArray *payloadAllKeys = [NSArray arrayWithArray:[userInfo allKeys]];
// getting "acme1" parameter value...
if([payloadAllKeys containsObject:#"acme1"]){
acme1 = [userInfo valueForKey:#"acme1"]; // getting "ID value" as "acme1"
}
NSString *localizedAlertMessage=#"";
// getting "aps" parameter value...
if([payloadAllKeys containsObject:#"aps"]){
NSDictionary *apsDict = [NSDictionary dictionaryWithDictionary:[userInfo objectForKey:#"aps"]];
NSArray *apsAllKeys = [NSArray arrayWithArray:[apsDict allKeys]];
if([apsAllKeys containsObject:#"alert"]){
if([[apsDict objectForKey:#"alert"] isKindOfClass:[NSDictionary class]]){
NSDictionary *alertDict = [NSDictionary dictionaryWithDictionary:[apsDict objectForKey:#"alert"]];
NSArray *alertAllKeys = [NSArray arrayWithArray:[alertDict allKeys]];
if([alertAllKeys containsObject:#"action-loc-key"]){
action_loc_key = [alertDict valueForKey:#"action-loc-key"]; // getting "action-loc-key"
}
if([alertAllKeys containsObject:#"loc-args"]){
loc_args_array = [NSArray arrayWithArray:[alertDict objectForKey:#"loc-args"]]; // getting "loc-args" array
}
if([alertAllKeys containsObject:#"loc-key"]){
loc_key = [alertDict valueForKey:#"loc-key"]; // getting "loc-key"
}
if([loc_args_array count] == 1){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0]];
}
else if([loc_args_array count] == 2){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0],[loc_args_array objectAtIndex:1]];
}
else if([loc_args_array count] == 3){
localizedAlertMessage = [NSString stringWithFormat:NSLocalizedString(loc_key, nil),[loc_args_array objectAtIndex:0],[loc_args_array objectAtIndex:1],[loc_args_array objectAtIndex:2]];
}
}
else{
localizedAlertMessage = [apsDict objectForKey:#"alert"];
}
}
if([apsAllKeys containsObject:#"badge"]){
badge = [[apsDict valueForKey:#"badge"] intValue]; // getting "badge" integer value
}
if([apsAllKeys containsObject:#"sound"]){
sound = [apsDict valueForKey:#"sound"]; // getting "sound"
}
}
//======================== Start : Handling notification =====================
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateActive){ // application is already open
if(apnsAlert){
apnsAlert = nil;
}
if(action_loc_key){ // View Button title dynamic...
apnsAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"%# %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"],NSLocalizedString(#"NOTIFICATION", nil)] message:localizedAlertMessage delegate:self cancelButtonTitle:NSLocalizedString(#"CANCEL", nil) otherButtonTitles: NSLocalizedString(action_loc_key, nil),nil];
}
else{
apnsAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"%# %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"],NSLocalizedString(#"NOTIFICATION", nil)] message:localizedAlertMessage delegate:self cancelButtonTitle:NSLocalizedString(#"OK", nil) otherButtonTitles:nil];
}
[apnsAlert show];
}
else{ // application is in background or not running mode
[self apnsViewControllerRedirectingFor_loc_key:loc_key with_acme1:acme1];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if(alertView == apnsAlert){
if (buttonIndex == 1){
[self apnsViewControllerRedirectingFor_loc_key:loc_key with_acme1:acme1];
}
}
}
-(void) apnsViewControllerRedirectingFor_loc_key:(NSString *)loc_key_para with_acme1:(NSString *)acme1_para{
if([loc_key_para isEqualToString:#"NOTIFICATION_DETAIL_PAGE"]){
DetailPageClass *detailPage = [[DetailPageClass alloc] initWithNibName:#"DetailPageClass" bundle:nil];
[self.navigationcontroller pushViewController:detailPage animated:YES]; // use nav controller where you want to push...
}
else if([loc_key_para isEqualToString:#"NOTIFICATION_MAIN_PAGE"]){
}
...
}
To change the title of the button, use the action-loc-key key in the notification dictionary (see this section of the guide).
To do something when the notification is tapped, you can implement a few methods in your app delegate: Handling notifications.

Making selectedSegmentIndex select nothing after selection

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).