I have been trying to connect a switch to an SMS text which worked out fine, i was even able to save the state the switch was left in.
However now i need to save the state only if the SMS is sent, and if the user doesn't send the message but a switch is already turned on it should then alert them with a AlertView.
So far i have been able to save the state the switch was left it and connect a label to signify if it is "ON" or "OFF" in the SMS.
- (void)viewDidLoad {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
self->switch1.on = ([[standardDefaults stringForKey:#"switchKey"]
isEqualToString:#"On"]) ? (YES) : (NO);
if(switch1.on){
label.text = #"ON";
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:label.text forKey:#"labelkey"];
[defults synchronize];
} else label.text = #"OFF"; {
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
[defults setObject:label.text forKey:#"labelkey"];
[defults synchronize];
}
label.text = [[NSUserDefaults standardUserDefaults]objectForKey:#"labelkey"];
}
- (IBAction)switchChanged:(UISwitch *)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (sender.on == 0) {
label.text = #"OFF";
[standardDefaults setObject:#"Off" forKey:#"switchKey"];
} else if (sender.on == 1) {
label.text = #"ON";
[standardDefaults setObject:#"On" forKey:#"switchKey"];
}
[standardDefaults synchronize];
}
This is how i send the SMS.
- (IBAction)sendRequest:(id)sender
{
MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
messageVC.body = [#[label.text] componentsJoinedByString:#""];
messageVC.recipients = #[_phoneNumber.text];
messageVC.messageComposeDelegate = self;
[self presentViewController:messageVC animated:NO completion:NULL];
}
By using MFMessageComposeViewControllerDelegate delegate, you can find Message is sent or cancelled by user.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result
{
switch (result) {
case MessageComposeResultCancelled:
//show alert here as per your requirement break;
case MessageComposeResultFailed:
{
UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed to send SMS!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[warningAlert show];
break;
}
case MessageComposeResultSent:
break;
default:
break;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Refer this link -> Send sms
Related
i am newbie on ios programming and this is my first time to use in app purchases. All of my IAPs are consumable and i have no error on my code. However, somethings are wrong. Because i tested my IAPs with sandbox environment and when i tried to purchase my first item which is tier 1, alert view showed me tier 5 item.
You can check all of my code about IAP:
#interface ViewController (){
NSString *currencyString;
SKProduct *validProduct;
}
- (void)validateReceiptForTransaction:(SKPaymentTransaction *)transaction {
VerificationController * verifier = [VerificationController sharedInstance];
[verifier verifyPurchase:transaction completionHandler:^(BOOL success) {
if (success) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Complete"
message:#"Transaction successful!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
[self provideContentForProductIdentifier:transaction.payment.productIdentifier];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Purchase Unsuccessful"
message:#"Your purchase failed. Please try again."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
}];
}
- (void)provideContentForProductIdentifier:(NSString *)productIdentifier {
if ([productIdentifier isEqualToString:#"100LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 100;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"500LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 500;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"1000LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 1000;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"5000LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 5000;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"10000LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 10000;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"50000LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 50000;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
else if ([productIdentifier isEqualToString:#"100000LJ"]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int j = [defaults integerForKey:#"j"];
j += 100000;
[defaults setInteger:j forKey:#"j"];
[defaults synchronize];
}
}
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:{
}
break;
case SKPaymentTransactionStatePurchased:{
[_activityView stopAnimating];
[self validateReceiptForTransaction:transaction];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
break;
case SKPaymentTransactionStateRestored:{
[_activityView stopAnimating];
[self validateReceiptForTransaction:transaction];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];}
break;
case SKPaymentTransactionStateFailed:{
[_activityView stopAnimating];
if (transaction.error.code != SKErrorPaymentCancelled) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Purchase Unsuccessful"
message:#"Your purchase failed. Please try again."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];}
break;
default:{}
break;
}
}
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
validProduct = nil;
int count = [response.products count];
if (count>0) {
validProduct = [response.products objectAtIndex:0];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setLocale:validProduct.priceLocale];
currencyString = [formatter stringFromNumber:validProduct.price];
if([validProduct.productIdentifier isEqual: #"100LJ"]){
[_storebuy1 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"500LJ"]){
[_storebuy2 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"1000LJ"]){
[_storebuy3 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"5000LJ"]){
[_storebuy4 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"10000LJ"]){
[_storebuy5 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"50000LJ"]){
[_storebuy6 setTitle:currencyString forState:UIControlStateNormal];
}
else if([validProduct.productIdentifier isEqual: #"100000LJ"]){
[_storebuy7 setTitle:currencyString forState:UIControlStateNormal];
}
}
}
I have 7 buttons to buy IAP items.
This is my button to buy tier 1 IAP item:
- (IBAction)storebuy1:(UIButton *)sender{
_activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[_activityView.layer setBackgroundColor:[[UIColor colorWithWhite: 0.0 alpha:0.30] CGColor]];
_activityView.center=self.view.center;
_activityView.hidesWhenStopped = YES;
[_activityView startAnimating];
[self.view addSubview:_activityView];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:#"100LJ"]];
request.delegate = self;
[request start];
if ([SKPaymentQueue canMakePayments]) {
SKPayment *payment = [SKPayment paymentWithProduct:validProduct];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Prohibited"
message:#"Parental Control is enabled!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
}
}
Hope you can help me.
Best Regards,
Taha
Because validProduct is set to whatever it was last set to when productsRequest:didReceiveResponse: was called, and that is unlikely to be what you want.
In general, your approach is wrong. You should be making one SKProductsRequest for all of your product identifiers and then storing all of the products that you get back. You can loop over the products to update your button titles (sort the products first). When a button is pressed you should then find the product with the appropriate identifier and create your SKPayment from that.
So, get rid of SKProduct *validProduct; and store the products in an array or a dictionary instead.
This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I'm having trouble in create a NSArray class Method with Text Fields strings to use in another views controllers classes.
Let me show you what i have done:
First,in settings view controller, i'm collecting information in 3 text fields and saving with NSUserdefaults:
- (void)viewDidLoad
{
// Get the stored data before the view loads
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *toEmail = [defaults objectForKey:#"toEmail"];
NSString *ccEmail = [defaults objectForKey:#"ccEmail"];
NSString *bccEmail = [defaults objectForKey:#"bccEmail"];
// Update the UI elements with the saved data
self.toEmailTextField.text = toEmail;
self.ccEmailTextField.text = ccEmail;
self.bccEmailTextField.text = bccEmail;
[super viewDidLoad];
[self sideBarButton];
[self dismissTextFields];
}
- (IBAction)toEmailAction:(id)sender {
NSString *toEmail = self.toEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:toEmail forKey:#"toEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
- (IBAction)ccEmailAction:(id)sender {
NSString *ccEmail = self.ccEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:ccEmail forKey:#"ccEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
- (IBAction)bccEmailAction:(id)sender {
NSString *bccEmail = self.bccEmailTextField.text;
// Store the data
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:bccEmail forKey:#"bccEmail"];
[defaults synchronize];
NSLog(#"Data saved");
}
Second I have another view controller with email API where I need to use the strings save with NSUserdefault in the settings view controller.(marked as text 1, text 2, and text 3)
#pragma mark - Email
- (IBAction)showEmail:(id)sender {
// Email Subject
NSString *emailTitle = #"GliLog Email";
// Email Content
NSString *messageBody = #"GliLog Email Test!!!";
// To address
NSArray *toRecipent = [NSArray arrayWithObject:#"text 1"];
NSArray *ccRecipient = [NSArray arrayWithObject:#"text 2"];
NSArray *bccRecipient = [NSArray arrayWithObject:#"text 3"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipent];
[mc setCcRecipients:ccRecipient];
[mc setBccRecipients:bccRecipient];
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:NULL];
}
- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
case MFMailComposeResultCancelled:
NSLog(#"Mail cancelled");
break;
case MFMailComposeResultSaved:
NSLog(#"Mail saved");
break;
case MFMailComposeResultSent:
NSLog(#"Mail sent");
break;
case MFMailComposeResultFailed:
NSLog(#"Mail sent failure: %#", [error localizedDescription]);
break;
default:
break;
}
// Close the Mail Interface
[self dismissViewControllerAnimated:YES completion:NULL];
}
How can i "pass" the strings from settings view controller to another view.
Best regards
You already have the answer in your first view, when reading the NSUserDefaults and storing to the strings:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *toEmail = [defaults objectForKey:#"toEmail"];
NSString *ccEmail = [defaults objectForKey:#"ccEmail"];
NSString *bccEmail = [defaults objectForKey:#"bccEmail"];
Just apply the same thing in second view controller,
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *toRecipent = [NSArray arrayWithObject:[defaults objectForKey:#"toEmail"]];
NSArray *ccRecipient = [NSArray arrayWithObject:[defaults objectForKey:#"ccEmail"]];
NSArray *bccRecipient = [NSArray arrayWithObject:[defaults objectForKey:#"bccEmail"]];
if you are storing the data in the NSUserDefaults, just get the value from it.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString * toEmail = [defaults objectForKey:#"toEmail"];
NSString * ccEmail = [defaults objectForKey:#"ccEmail"];
A nice and simple tutorial about NSUserDefaults
I'm creating a simple game app.
When the user click on the first button and the int click is 0, the he can click on the second button, and so on.
If the user firstly click on the second button and then on the first, his lifes will decreasing.
I'm having problems when the user reaches 0 lifes and the View returns on the first page.
Then when I click on the button to play again, I have 0 lifes and don't 3!
Here is my code:
#implementation livello1
int click=0;
int lifes=3;
-(void)updateLifes:(int)lifes{
if (lifes==1){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"1" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==2){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"2" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==3){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else if (lifes==0){
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifes=3;
[self showLifes];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
gioca *giocaview = [[gioca alloc] initWithNibName:nil bundle:nil];
giocaview.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:giocaview animated:YES completion:nil];
}
}
-(void)showLifes{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"1"]) {
lifes=1;}
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"2"]) {
lifes=2;}
if ([[standardDefaults stringForKey:#"Userlifes"] isEqualToString:#"3"]) {
lifes=3;}
lifesLabel.text = [NSString stringWithFormat:#"%i",lifes];
}
- (IBAction)press1:(UIButton *)button1{
if ((button1.selected=YES && click==0)){
click=1;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes:(lifes)];
}
}
- (IBAction)press2:(UIButton *)button2{
if ((button2.selected =YES) && click==1){
click=2;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes:(lifes)];
}
}
- (void)viewDidLoad{
[super viewDidload];
[self showLifes];
}
Create another button for "Play Again" and link it to -(IBAction)buttonPressed:(UIButton *)playAgain and in that function reset the value of life to 3. And you don't need to pass lifes as it is a global variable (though that is not a very good practice). Though I am not really sure about your logic/ implementation for the click, you can use the following (slightly optimised) code :
#implementation livello1
int click=0;
int lifes=3;
-(void)updateLifes{
if (lifes!=0) {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
[standardDefaults setInteger:lifes forKey:#"UserLifes"];
[standardDefaults synchronize];
[self showLifes];
livello1 *livello1view = [[livello1 alloc] initWithNibName:nil bundle:nil];
livello1view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:livello1view animated:YES completion:nil];
}
else {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifes=3;
[self showLifes];
[standardDefaults setObject:#"3" forKey:#"UserLifes"];
[standardDefaults synchronize];
gioca *giocaview = [[gioca alloc] initWithNibName:nil bundle:nil];
giocaview.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:giocaview animated:YES completion:nil];
}
}
-(void)showLifes{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
lifesLabel.text = [NSString stringWithFormat:#"%i",[standardDefaults integerForKey:#"Userlifes"]];
}
- (IBAction)press1:(UIButton *)button1{
if ((button1.selected=YES && click==0)){
click=1;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes];
}
}
- (IBAction)press2:(UIButton *)button2{
if ((button2.selected =YES) && click==1){
click=2;
}
else{
lifes=lifes-1;
click=0;
[self updateLifes];
}
}
- (IBAction)buttonPressed:(UIButton *)playAgain{ //the new function
lifes = 3;
click = 0;
[self updateLifes];
}
- (void)viewDidLoad{
[super viewDidload];
[self showLifes];
}
on playAgain Button click, setLife counter to 3.
In my iOS iPhone app I use facebook connect. The SSO works wonderfully, I can post to wall etc., But there is one problem:
I start my app
allow facebook to connect
everything is fine in the app
BUT NOW ...
I delete the application on the facebook website!
If I start my app now - the NSLOG says, the FB-Connections is OK. ..?
So I thought, If I delete the applications online in my account, the iphone app has NO validSession and has to ask for a new login, but this failed.
What is wrong? How can I check that in the right way? Or how log is the sessionValid? Is there a timelimit before the method will run again? So was my check (delete online, start app again) to quick?
---- UPDATE:
- (void)fbLogin:(id)sender{
NSLog(#"FB Login Alert");
[self checkForPreviouslySavedAccessTokenInfo];
if (!isConnected == YES) {
NSLog(#"NO - Facebook Connection");
UIAlertView *popupFacebook = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Headline_FacebookL", #"Headline")
message:NSLocalizedString(#"Facebook-Text", #"Facebook")
delegate:self
cancelButtonTitle:NSLocalizedString(#"later",#"Facebook Login später")
otherButtonTitles:NSLocalizedString(#"Facebook",#"Login"), nil];
popupFacebook.tag = alertFacebook;
[popupFacebook show];
[popupFacebook release];
}
else{
NSLog(#"Facebook Connection OK");
}
}
(void)checkForPreviouslySavedAccessTokenInfo:
-(void)checkForPreviouslySavedAccessTokenInfo{
// Initially set the isConnected value to NO.
isConnected = NO;
NSLog(#"FB Status erst mal auf NEIN");
// Check if there is a previous access token key in the user defaults file.
appDelegate.facebook = [[Facebook alloc] initWithAppId:#"XXXXXXXXX" andDelegate:(AppDelegate *) [[UIApplication sharedApplication] delegate]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
appDelegate.facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
appDelegate.facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
// Check if the facebook session is valid.
// If it’s not valid clear any authorization and mark the status as not connected.
if (![appDelegate.facebook isSessionValid]) {
//[facebook authorize:permissions];
isConnected = NO;
NSLog(#"FB NO");
}
else {
isConnected = YES;
NSLog(#"FB YES");
}
}
SWITCH:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(#"clicking");
//NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
if (alertView.tag == alertWelcome ) {
if (buttonIndex == 0) {
NSLog(#"close");
}
}
else if (alertView.tag == alertFacebook ) {
if (buttonIndex == 0) {
NSLog(#"später");
}
if (buttonIndex == 1) {
//self.label.text = NSLocalizedString(#"Facebook",#"Login"),
[self fbActive:nil];
NSLog(#"Login to FB");
}
}
}
Permissions:
-(void)fbActive:(id)sender{
if (![appDelegate.facebook isSessionValid]) {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_likes",
#"read_stream",
#"user_status",
#"publish_stream",
//#"publish_actions",
//#"manage_pages",
#"read_requests",
nil];
[appDelegate.facebook authorize:permissions];
NSLog(#"FB - Permissions");
[permissions release];
}
}
The game that I am creating has a highScore integer variable that gets assigned when the player loses. I am using NSUsersDefaults class to save my high score. Here is my code that I am using:
-(void)saveScore {
[[NSUserDefaults standardUserDefaults] setInteger:score forKey:#"highScore"];
[defaults setInteger:score forKey:#"highScore"];
[defaults synchronize];
NSLog(#"High Score: %i ", highScore);
}
-(IBAction)buttonReleased:(id)sender {
[stopWatchTimer invalidate];
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
NSString *label0 = #"Hold to Start";
[labelText setText:label0];
if (score > 0) {
score--;
}
else {
score = 0;
NSLog(#"Changed score to 0");
}
if (score > highScore) {
[self saveScore];
NSString *scoreMessage =[[NSString alloc] initWithFormat:#"Congrats! You have a new High Score! Click Share High Score to share your score of: %i",score];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"High Score!" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
score = 0;
}
else {
NSString *scoreMessage =[[NSString alloc] initWithFormat:#"Game Over! Your score was: %i",score];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"GAME OVER!" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:#"Try Again" otherButtonTitles: nil];
[alert show];
[alert release];
score = 0;
}
- (void)viewDidLoad
{
[super viewDidLoad];
int highscore = [[NSUserDefaults standardUserDefaults] integerForKey: #"highScore"];
[stopWatchTimer invalidate];
stopWatchTimer=nil;
}
I have been wrestling with this for HOURS! What am I doing wrong?! Note: Can you explain it as simply as possible.
Thanks!
-Matt
Reading it:
int highscore = [[NSUserDefaults standardUserDefaults] integerForKey: #"highScore"];
It will most likely be the default value of int (i.e. 0) when the file is blank.
Also don't forget to force a write of your defaults to "disk" with synchronize:
-(void)saveScore {
NSUSerDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:score forKey:#"highScore"];
[defaults synchronize];
}
You can load the highscore either in viewDidLoad or even in your init (or initWithNibName) method since this part isn't dependent on your view being loaded.
You could declare a property on your Scores view that you set in the viewDidLoad method. Alternatively you could expose the UILabel of that scores class (if that's what you use) as a property of your scores class.
- (void)viewDidLoad:
{
...
self.scoresView.textLabel.text = [NSString stringWithFormat:#"%d", highScore];
...
}
There is a really simple highscore management system which I have written it even has online support. You can find it https://github.com/faizanaziz/HighScore