Have a question on how can I update my formula by NSUserDefault. So I have two text field which needs to keep my Formula uptodate. So the user types in there number (value) then that numbers needs to go to my formula but the formula only showing me the distance value :).
I think the problem may lie here:
int gas = [[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"];
int money = [[NSUserDefaults standardUserDefaults] objectForKey:#"Money"];
You are writing out to your NSUserDefaults directly from your textField.text, often with 0.00 formatting, but you are reading it in as an int. It is stored as a NSString likely. You should store and read it as a NSNumber.
Going In:
NSNumber *foo = [NSNumber numberWithInteger:TextGas.text.integerValue];
NSNumber *bar = [NSNumber numberWithDouble:TextMoney.text.doubleValue];
[defaults setObject:foo forKey:#"Gas"];
[defaults setObject:bar forKey:#"Money"];
Coming out:
NSNumber *gas = [[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"];
NSNumber *money = [[NSUserDefaults standardUserDefaults] objectForKey:#"Money"];
gas.integerValue;
money.doubleValue;
I tried your code with some changes. Here are my .h file and .m files. Try this. Now also I didn't understand what your trying to find out, but this code gives me the values not a nan. While you writing code, don't forget to start your variable name in small letter that is a standard way. And also use self if you set a variable as property.
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface ViewController : UIViewController
<UITextFieldDelegate,CLLocationManagerDelegate>{
IBOutlet MKMapView *mapView;
IBOutlet UITextField *textGas;
IBOutlet UITextField *textMoney;
IBOutlet UITextField *textTotal;
IBOutlet UITextField *textDistance;
}
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
double totalDistance;
float gas,money;
}
#end
#implementation ViewController
#synthesize locationManager;
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[self.locationManager startUpdatingLocation];
//set default value for Gas
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"]) {
[[NSUserDefaults standardUserDefaults] setObject:#"1.0" forKey:#"Gas"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//set default value for Money
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"Money"]) {
[[NSUserDefaults standardUserDefaults] setObject:#"1.0" forKey:#"Money"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
gas = [[[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"] floatValue];
money = [[[NSUserDefaults standardUserDefaults] objectForKey:#"Money"] floatValue];
textGas.text = [NSString stringWithFormat:#"%.1f",gas];
textMoney.text = [NSString stringWithFormat:#"%.1f",money];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"])
textGas.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"Gas"];
else
textGas.text = #"0";//set default value
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"Money"])
textMoney.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"Money"];
else
textMoney.text = #"0.01";//set default value
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[textMoney resignFirstResponder];
[textGas resignFirstResponder];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
exit(0);
}
if (buttonIndex == 0) {
[self.locationManager stopUpdatingLocation];
mapView.showsUserLocation = NO;
}
}
#pragma mark - UITextFieldDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if ([textField.text intValue] == 0) {
textGas.text = [NSString stringWithFormat:#"%.1f",gas];
textMoney.text = [NSString stringWithFormat:#"%.1f",money];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"Value cann't be zero."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
alert = nil;
return;
}
if (![textField.text length]) {
textGas.text = [NSString stringWithFormat:#"%.1f",gas];
textMoney.text = [NSString stringWithFormat:#"%.1f",money];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:#"Value cann't be empty."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
alert = nil;
return;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (textField == textGas) {
[defaults setObject:textGas.text forKey:#"Gas"];
gas = [textGas.text floatValue];
}
else if (textField == textMoney)
{
[defaults setObject:textMoney.text forKey:#"Money"];
money = [textMoney.text floatValue];
}
[defaults synchronize];
}
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
{
// Zoom to the current user location.
MKCoordinateRegion userLocation = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 1200.0, 1200.0);
[mapView setRegion:userLocation animated:NO];
mapView.showsUserLocation = YES;
}
if (!oldLocation)
totalDistance = 0.0;
else
totalDistance += [newLocation distanceFromLocation:oldLocation];
double distance = totalDistance*0.00062137119;
textTotal.text = [[ NSString alloc] initWithFormat:#"$%.2f", distance/gas*money];
textDistance.text = [NSString stringWithFormat:#"%.2f Miles", distance];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And the result in Simulator is
Don’t forget to connect delegates and IBOutlet from interface builder.
Related
At the most recent Google IO, they released the Google Places API for iOS. I'm having trouble, though, when the location used to pick places isn't hard coded. I want to find places nearby with the Place Picker.
Here's a screenshot of how the current location isn't picked up:
Here's my code:
FirstViewController.h:
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
#import <CoreLocation/CoreLocation.h>
#interface FirstViewController : UIViewController
//<GMSMapViewDelegate>
#property (nonatomic,retain) CLLocationManager *locationManager;
#property (strong, nonatomic) NSString *name2;
#property (strong, nonatomic) NSString *address2;
#property (strong, nonatomic) NSString *cat;
//#property (strong, nonatomic) NSString *lat;
//#property (strong, nonatomic) NSString *lon;
//
#property double latitude;
#property double longitude;
#property (weak, nonatomic) IBOutlet UILabel *nameLabel;
#property (weak, nonatomic) IBOutlet UILabel *addressLabel;
#property (weak, nonatomic) IBOutlet UILabel *catLabel;
#end
FirstViewController.m:
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController {
GMSPlacePicker *_placePicker;
GMSMapView *mapView_;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
// locationManager.delegate = self; // we set the delegate of locationManager to self.
// locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy
// [locationManager requestAlwaysAuthorization];
//
// [locationManager startUpdatingLocation]; //requesting location updates
mapView_.settings.myLocationButton = YES;
mapView_.myLocationEnabled = YES;
mapView_.hidden = YES;
NSLog(#"User's location: %#", mapView_.myLocation);
}
//
//-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
// UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"There was an error retrieving your location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// [errorAlert show];
// NSLog(#"Error: %#",error.description);
//}
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//{
// CLLocation *crnLoc = [locations lastObject];
// _lat = [NSString stringWithFormat:#"%.8f",crnLoc.coordinate.latitude];
// _lon = [NSString stringWithFormat:#"%.8f",crnLoc.coordinate.longitude];
// double _latitude = [_lat doubleValue];
// double _longitude = [_lon doubleValue];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//- (NSString *)deviceLocation
//{
// NSString *theLocation = [NSString stringWithFormat:#"%f, %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
// return theLocation;
//}
// Add a UIButton in Interface Builder to call this function
- (IBAction)pickPlace:(UIButton *)sender {
CLLocation *myLocation = mapView_.myLocation;
// CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.788204, -122.411937);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(myLocation.coordinate.latitude, myLocation.coordinate.longitude);
CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(center.latitude + 0.001,
center.longitude + 0.001);
CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(center.latitude - 0.001,
center.longitude - 0.001);
GMSCoordinateBounds *viewport = [[GMSCoordinateBounds alloc] initWithCoordinate:northEast
coordinate:southWest];
GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:viewport];
_placePicker = [[GMSPlacePicker alloc] initWithConfig:config];
[_placePicker pickPlaceWithCallback:^(GMSPlace *place, NSError *error) {
if (error != nil) {
NSLog(#"Pick Place error %#", [error localizedDescription]);
return;
}
if (place != nil) {
_name2 = place.name;
NSLog(place.name);
self.nameLabel.text = place.name;
_address2 = place.formattedAddress;
self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:#", "]
componentsJoinedByString:#"\n"];;
NSLog(place.formattedAddress);
_cat = place.types[0];
self.catLabel.text = place.types[0];
NSLog(_cat);
} else {
_name2 = #"No place selected";
_address2 = #"";
}
}];
}
- (void)requestAlwaysAuthorization
{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
}
#end
Also, is there any way I can use the place picker for the apple watch? Thanks!
By adding Core Location to the app I was able to get the coordinates for current location to be used in the place picker. Here's my code:
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(_locationManager.location.coordinate.latitude, _locationManager.location.coordinate.longitude);
GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:nil];
IOS Game
I am creating a game were there is a button and there aim of the game is see how much taps you can get before the time runs out
But i have a problem i need to recored the high score, how can i do that.
.h code
#import <UIKit/UIKit.h>
#interface errrViewController : UIViewController{
IBOutlet UILabel *label;
IBOutlet UILabel *timerLabel;
NSInteger count;
NSInteger seconds;
NSTimer *timer; //ADD THIS!!
}
- (IBAction) buttonPressed;
- (void)setupGame;
- (void)subtractTime;
#end
m. code
#import "errrViewController.h"
#interface errrViewController ()
#end
#implementation errrViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setupGame];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//Implementing our method
- (IBAction)buttonPressed{
count++;
label.text = [NSString stringWithFormat:#"Score\n%i",count];
}
- (void)setupGame{
seconds = 30;
count = 0;
timerLabel.text = [NSString stringWithFormat:#"Time: %i",seconds];
label.text = [NSString stringWithFormat:#"Score\n%i",count];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(subtractTime) userInfo:nil repeats:YES];
}
- (void)subtractTime{
seconds--;
timerLabel.text = [NSString stringWithFormat:#"Time: %i",seconds];
if(seconds == 0){
[timer invalidate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!" message:[NSString stringWithFormat:#"You scored %i points",count] delegate:self cancelButtonTitle:#"Play Again" otherButtonTitles:nil];
[alert show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[self setupGame];
}
#end
#import "errrViewController.h"
#interface errrViewController ()
#end
#implementation errrViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setupGame];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//Implementing our method
- (IBAction)buttonPressed{
count++;
label.text = [NSString stringWithFormat:#"Score\n%i",count];
}
- (void)setupGame{
seconds = 30;
count = 0;
timerLabel.text = [NSString stringWithFormat:#"Time: %i",seconds];
label.text = [NSString stringWithFormat:#"Score\n%i",count];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(subtractTime) userInfo:nil repeats:YES];
}
- (void)subtractTime{
seconds--;
timerLabel.text = [NSString stringWithFormat:#"Time: %i",seconds];
if(seconds == 0){
[timer invalidate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!" message:[NSString stringWithFormat:#"You scored %i points",count] delegate:self cancelButtonTitle:#"Play Again" otherButtonTitles:nil];
[alert show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[self setupGame];
}
#end
Please explain how to do this in steps
Please provide any links if possible that can help me
You can do this by saving the highscore to a plist file, in the form of a NSDictionary. For example:
int highscore; //your highscore variable, which I believe you can calculate yourself
Then you can have a save function like:
-(void) saveHighscore{
NSDictionary* highscoreDict = [[NSDictionary alloc] initWithObjectsAndKeys: [NSString stringWithFormat:#"%d", highscore], #"Highscore",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//get the path for the documents directory
NSString* filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: #"Highscore.plist"];
//Check if file exists
if([[NSFileManager defaultManager]fileExistsAtPath:filePath]){
//delete it if it does, because we're going to replace it anyway
[[NSFileManager defaultManager]removeItemAtPath:filePath error:nil];
}
[highscoreDict writeToFile:filePath atomically:YES]; // write to file
}
And you can have a load highscore function like:
-(int) loadHighscore{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: #"Highscore.plist"];
//Check if file exists
if([[NSFileManager defaultManager]fileExistsAtPath:filePath]){
NSDictionary* highscoreDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
//Retrieve the value of highscore from your file
return [[highscoreDict valueForKey: #"Highscore"]intValue];
}
//Otherwise return 0 as the highscore
return 0;
}
And add [self loadHighscore]; in your viewDidLoad function.
Hope this helps.
I would like to stop my music playing from another view by using delegates. I already have that setup and i know there is this option...
- (void)viewWillDisappear:(BOOL)animated{
[player stop]; ///(my players name here and command to stop the player)
}
However i do not want to use that function because i have the music playing throughout. I have already added code to ensure my player does not overlap. But when i do want to stop my music i want to do so in a different view. I have tried the '[player stop];' function when the delegate is called but it does not work.
Can anyone help?
Thanks in advanced...
EDIT
HERE IS THE CODE FOR MY OPTIONS PAGE.H FILE:
#protocol onHandlerDelegate <NSObject>
- (void)off:(BOOL)success;
- (void)on:(BOOL)success;
-(void)volumeValueChange:(UISlider *)sender;
#end
#import <UIKit/UIKit.h>
#interface OptionsPage : UIViewController{
IBOutlet UISlider *VolumeSlider;
NSTimer *VolumeTimer;
IBOutlet UISwitch *onoroffmusic;
}
-(IBAction) UIBarButtonItem:(id)sender;
-(IBAction) SwitchMusic:(id)sender;
-(IBAction)changevolume:(id)sender;
#property (nonatomic, retain) UISwitch *onoroffmusic;
#property (nonatomic, strong) id<onHandlerDelegate> delegatePpty1;
#end
HERE IS MY OPTIONS PAGE .M FILE:
#import "OptionsPage.h"
#import "ViewController.h"
#interface OptionsPage ()
#end
#implementation OptionsPage
#synthesize onoroffmusic;
#synthesize delegatePpty1;
- (IBAction)changevolume:(id)sender{
int volume = VolumeSlider.value;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithInt:volume] forKey:#"volume"];
[defaults synchronize];
[[self delegatePpty1]volumeValueChange:(VolumeSlider)];
}
-(IBAction) SwitchMusic:(id)sender{
if (onoroffmusic.on) {
[[self delegatePpty1] on:YES];
printf("done");
onoroffmusic.on = YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"off"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"on"];
[defaults synchronize];
}
else {
/// do nothing
[[self delegatePpty1] off:YES];
printf("off");
onoroffmusic.on = NO;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"on"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"off"];
[defaults synchronize];
ViewController *home = [[ViewController alloc] initWithNibName:nil bundle:nil];
[home.player stop];
}
}
-(IBAction) UIBarButtonItem:(id)sender{
ViewController *Backbutton = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:Backbutton animated:YES completion:nil];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad{
VolumeSlider.value = 0.3;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs valueForKey:#"volume"];
if(object == nil){
VolumeSlider.value = 0.3;
}
else{
VolumeSlider.value = [[[NSUserDefaults standardUserDefaults] objectForKey:#"volume"] intValue];
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
BOOL restoredBoolValue2 = [[defaults2 objectForKey:#"off"] boolValue];
BOOL restoredBoolValue1 = [[defaults2 objectForKey:#"on"] boolValue];
if (restoredBoolValue2) {
////donothing
onoroffmusic.on = FALSE;
}
if (restoredBoolValue1) {
////donothing
onoroffmusic.on = TRUE;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Within the two files i declare a delegate and my switches. Now just to receive that delegate in my view controller:
MY VIEWCONNTROLLER .H FILE:
#import "OptionsPage.h"
#interface ViewController : UIViewController <onHandlerDelegate>{
AVAudioPlayer *player;
}
#property (nonatomic, retain) AVAudioPlayer *player;
#end
HERE IS MY .M FILE:
Firstly I
#synthesize player;
Then check if my delegates have been called by using:
-(void)volumeValueChange:(UISlider *)sender
{
if (sender.value > 0.3) {
player.volume = sender.value;
}
else{
player.volume = 0.3;
}
}
-(void)on:(BOOL)success{
NSLog(#"Delegate Method Called");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"mykey1"];
[self play];
[player play];
}
-(void)off:(BOOL)success{
NSLog(#"Delegate Method Called");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:#"mykey1"];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:#"mykey"];
[player stop];
player = nil;
[defaults removeObjectForKey:#"music"];
}
I then load the bool value of my nsuserdefults by using this:
- (void)viewDidLoad
{
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"mykey"] == nil ) {
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"music"] == nil) {
[self play];
}
}
}
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
BOOL restoredBoolValue2 = [[defaults2 objectForKey:#"mykey"] boolValue];
if (restoredBoolValue2) {
////donothing
[player stop];
}
BOOL restoredBoolValue1 = [[defaults2 objectForKey:#"mykey1"] boolValue];
if (restoredBoolValue1){
[self play];
}
And i have my play void function
-(void)play{
if ([[NSUserDefaults standardUserDefaults] stringForKey:#"music"] == nil) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/Music.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
player.numberOfLoops = -1;
[player play];
player.volume = 0.3;
player.currentTime = 0.0;
[[NSUserDefaults standardUserDefaults] setObject:#"-" forKey:#"music"];
}
else {
[player stop];
}
}
and lastly in my app delegate.m file i :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:#"music"];
}
Make player a property and stop it like this:
[anotherView.player stop];
First you need to change onHandlerDelegate from strong to weak because it is a delegate.
Secondly you need an instance of OptionsPage on the second view controller and you need to implement the delegate and do optionPage.delegate = self after it this will work.
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
I have the latitude & Longitude data of a location, how can I make it a Google Maps link, when the user clicks on share and choose option like email.
Here is the code that I use to get location data:
// Here is the .h file
#interface locate : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate>
{
CGPoint gestureStartPoint;
CLLocationManager *locationManager;
CLLocation *startingPoint;
UILabel *latitudeLabel;
UILabel *longitudeLabel;
UILabel *altitudeLabel;
MKMapView *mapView;
}
#property (assign) CGPoint gestureStartPoint;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, retain) CLLocation *startingPoint;
#property (nonatomic, retain) IBOutlet UILabel *latitudeLabel;
#property (nonatomic, retain) IBOutlet UILabel *longitudeLabel;
#property (nonatomic, retain) IBOutlet UILabel *altitudeLabel;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#end
// Here is the .m file
#import "locate.h"
#implementation locate
#synthesize gestureStartPoint,locationManager,startingPoint,latitudeLabel,longitudeLabel,altitudeLabel,mapView;
- (void)dealloc
{
[locationManager release];
[startingPoint release];
[latitudeLabel release];
[longitudeLabel release];
[altitudeLabel release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
if (startingPoint == nil)
self.startingPoint = newLocation;
NSString *latitudeString = [[NSString alloc] initWithFormat:#"%g\u00B0",
newLocation.coordinate.latitude];
latitudeLabel.text = latitudeString;
[latitudeString release];
NSString *longitudeString = [[NSString alloc] initWithFormat:#"%g\u00B0",
newLocation.coordinate.longitude];
longitudeLabel.text = longitudeString;
[longitudeString release];
NSString *altitudeString = [[NSString alloc] initWithFormat:#"%gm",
newLocation.altitude];
altitudeLabel.text = altitudeString;
[altitudeString release];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSString *errorType = (error.code == kCLErrorDenied) ?
#"Access Denied" : #"Unknown Error";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error getting Location"
message:errorType
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)viewDidLoad
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
mapView.delegate = self;
mapView.mapType = MKMapTypeStandard;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.locationManager = nil;
self.latitudeLabel = nil;
self.longitudeLabel = nil;
self.altitudeLabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#end
Now please someone help me on how can I use the location data to create Google Maps link?
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[txtf_mapsearch.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
You need this code.
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/maps?q=%1.6f,%1.6f",
newLocation.coordinate.latitude,
newLocation.coordinate.longitude];
linkMap.text = googleMapsURLString;
Try this
NSString *googleMapsURLString = [NSString stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",
self.currentLocation.coordinate.latitude,
self.currentLocation.coordinate.longitude,
longitude,
latitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapsURLString]];
where latitude and longitude are the point of interest.