this was working earlier but now it is not because it does not recognize the settings in the first .m file below. I did #import Setting.h but it still does not work. Please help!
Here is the .h file:
#import <UIKit/UIKit.h>
#import "EditNameViewController.h"
#interface SettingsViewController : UIViewController <EditNameDelegate>{
IBOutlet UIButton *froshsched;
IBOutlet UIButton *uppersched;
}
.m file. it says settings and 'settings are undeclared
#import "SettingsViewController.h"
#import "Settings.h"
#interface SettingsViewController ()
#end
#implementation SettingsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Settings", #"Settings");
self.tabBarItem.image = [UIImage imageNamed:#"spanner"];
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
-(IBAction)froshsched{
Settings *settings = [Settings sharedInstance];
settings.timelabelfirst = #"12:35";
settings.timelabelsecond = #"1:25";
[[Settings sharedInstance] save];
}
-(IBAction)uppersched{
Settings *settings = [Settings sharedInstance];
settings.timelabelfirst = #"12:10";
settings.timelabelsecond = #"1:00";
[[Settings sharedInstance] save];
}
-(IBAction)editclass{
EditNameViewController*vc2 = [[EditNameViewController alloc] init];
vc2.delegate = self;
[self presentModalViewController:vc2 animated:YES];
}
-(void)dismiss{
[self dismissModalViewControllerAnimated:YES];
}
#end
-(IBAction)editclass;
-(IBAction)froshsched;
-(IBAction)uppersched;
here is the Settings.h
#import <Foundation/Foundation.h>
#interface Settings : NSObject
#property (nonatomic) NSString *redClassName, *orangeClassName, *yellowClassName, *greenClassName, *ltblueClassName, *dkblueClassName, *purpleClassName, *pinkClassName, *timelabelfirst, *timelabelsecond;
+(Settings*)sharedInstance;
-(void)save;
#end
and lastly here is the Settings.m file, I feel like I am missing something simple, thanks
#import "Settings.h"
#implementation Settings
#synthesize redClassName, orangeClassName, yellowClassName, greenClassName, ltblueClassName, dkblueClassName, purpleClassName, pinkClassName, timelabelfirst, timelabelsecond;
-(id)init{
self = [super init];
if(self){
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
redClassName = [defaults objectForKey:#"kredClass"];
orangeClassName = [defaults objectForKey:#"korangeClass"];
yellowClassName = [defaults objectForKey:#"kyellowClass"];
greenClassName = [defaults objectForKey:#"kgreenClass"];
ltblueClassName = [defaults objectForKey:#"kltblueClass"];
dkblueClassName = [defaults objectForKey:#"kdkblueClass"];
purpleClassName = [defaults objectForKey:#"kpurpleClass"];
pinkClassName = [defaults objectForKey:#"kpinkClass"];
timelabelfirst = [defaults objectForKey:#"ktime1"];
timelabelsecond = [defaults objectForKey:#"ktime2"];
}
return self;
}
+(Settings*)sharedInstance{
static Settings *sharedSettings;
if(!sharedSettings) sharedSettings = [[Settings alloc] init];
return sharedSettings;
}
-(void)save{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:redClassName forKey:#"kredClass"];
[defaults setObject:orangeClassName forKey:#"korangeClass"];
[defaults setObject:yellowClassName forKey:#"kyellowClass"];
[defaults setObject:greenClassName forKey:#"kgreenClass"];
[defaults setObject:ltblueClassName forKey:#"kltblueClass"];
[defaults setObject:dkblueClassName forKey:#"kdkblueClass"];
[defaults setObject:purpleClassName forKey:#"kpurpleClass"];
[defaults setObject:pinkClassName forKey:#"kpinkClass"];
[defaults setObject:timelabelfirst forKey:#"ktime1"];
[defaults setObject:timelabelsecond forKey:#"ktime2"];
[defaults synchronize];
}
#end
You didn't give us EditNameController (with its delegate). In any case I copied and pasted all of your code above and by commenting out EditNameController related items it all compiled fine (except of course these lines floating at the bottom of your file:
-(IBAction)editclass;
-(IBAction)froshsched;
-(IBAction)uppersched;
You also didnt show a "#end" at the bottom of SettingsViewController.h (which I added before compiling).
Related
I am writing an application in Objective C and I keep getting a Use of Undeclared Identifier 'startClient' error. I have attached a link to my project file and the tutorial link is here: https://www.sinch.com/tutorials/building-one-button-app-conference-calling/
https://drive.google.com/file/d/0B5loU41SFmzDZ2RNbWJsR0xoSk0/view?usp=sharing
The relevant portion of my code is here...
#import <QuartzCore/QuartzCore.h>
#import "ConferenceViewController.h"
#import "LoginViewController.h"
#import <SinchCallingUIKit/SinchCallingUIKit.h>
#class ConferenceViewController;
#interface UIView ()
#end
#implementation ConferenceViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidAppear:(BOOL)animated
{
- (void)startClient {}{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[[CallingManager sharedManager] startClientWithKey:8b6893bf-41c6-4527-bc68-9d3703c13be3 secret:Ox18uwq7gkiAdeQYzntN6A== userName:[defaults stringForKey:#"userName"] sandbox:NO launchOptions:nil];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if ([defaults stringForKey:#"userName"] == nil)
{
[self performSegueWithIdentifier:#"login" sender:nil];
}
else
{
[self startClient];
}
}
You can't stick a function inside another function. You have the implementation of startClient inside of viewDidAppear.
I don't know what your viewDidAppear is supposed to do, but this will compile:
- (void)viewDidAppear:(BOOL)animated
{
if ([defaults stringForKey:#"userName"] == nil)
{
[self performSegueWithIdentifier:#"login" sender:nil];
}
else
{
[self startClient];
}
}
- (void)startClient
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[[CallingManager sharedManager] startClientWithKey:8b6893bf-41c6-4527-bc68-9d3703c13be3 secret:Ox18uwq7gkiAdeQYzntN6A== userName:[defaults stringForKey:#"userName"] sandbox:NO launchOptions:nil];
}
I made an AR app that recognize image and show the object recognized in an AlertView. In the AlertView I have 2 buttons: Add and Cancel, I'm using the UIAlertViewDelegate to understand which button the user pressed. If the user press the Add button, the object recognized will be stored in an array. I pass this array to another ViewController, in which I set up a TableView. On the bottom of this TableView there's a button "Pay" to go to another ViewController in which I display the total price of the object recognized. From the last ViewController I can press a button to pay the objects I selected by using the AR. Now when I press this button the app close this ViewController and go back to the first ViewController, but the array in which I stored the object that the AR recognized it's full. To delete the content of this array I thought that the best way is to use the delegation methods, so I made this:
PaymentViewController.h
#import <UIKit/UIKit.h>
#protocol PaymentViewControllerDelegate;
#interface PaymentViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *labelTotal;
- (IBAction)buttonClosePaymentVC:(id)sender;
- (IBAction)buttonPay:(id)sender;
#property(nonatomic,strong)NSString *total;
#property(assign) id<PaymentViewControllerDelegate> delegate;
#end
#protocol PaymentViewControllerDelegate <NSObject>
- (void)cleanReportArray;
#end
PaymentViewController.m
#import "PaymentViewController.h"
#interface PaymentViewController () <UIAlertViewDelegate>
#end
#implementation PaymentViewController
#synthesize delegate = _delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.labelTotal.text = self.total;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClosePaymentVC:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)buttonPay:(id)sender {
NSString *pay = [NSString stringWithFormat:#"Stai per pagare %#, procedi?", self.total];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:pay delegate:self cancelButtonTitle:#"Si" otherButtonTitles:#"No", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
// Procedura per il pagamento e cancellazione del file plist
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"objects.plist"];
NSError *error;
if (![[NSFileManager defaultManager]removeItemAtPath:path error:&error]) {
NSLog(#"Errore: %#", error);
}
__weak UIViewController *vcThatPresentedCurrent = self.presentingViewController;
[self dismissViewControllerAnimated:YES completion:^{
[vcThatPresentedCurrent dismissViewControllerAnimated:YES completion:nil];
}];
[self.delegate cleanReportArray];
}
if (buttonIndex == 1) {
// Non deve far nulla: fa scomparire l'UIAlertView
}
}
Here I post to you the method of the class that will use the delegate:
Interface of the ScannerViewController.m
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
In ViewDidLoad I inserted this rows:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
And in the ScannerViewController.m I implemented the method I declared in PaymentViewController.h:
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
I tested my app on my iPhone, the app works fine until I try to pay the objects I scanned by camera, indeed, I tried to pay the object, but it doesn't clean the array in which I stored the objects scanned.
What's wrong in my code? I used an tutorial on the web to understand better how the delegation method works. I hope you can help me to fix this issue, thank you
UPDATE:
here i will post my ScannerViewController code:
ScannerViewController.h
#import <UIKit/UIKit.h>
#interface ScannerViewController : UIViewController
#end
ScannerViewController.m
#import "ScannerViewController.h"
#import "PaymentViewController.h"
#import "ReportViewController.h"
#import "MSScannerSession.h"
#import "MSResult.h"
#import "XmlReader.h"
static int kMSScanOptions = MS_RESULT_TYPE_IMAGE |
MS_RESULT_TYPE_EAN8 |
MS_RESULT_TYPE_EAN13;
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
#implementation ScannerViewController {
MSScannerSession *_scannerSession;
NSString *nameOfObjectScanned;
XmlReader *reader;
NSMutableArray *arrayObjectAdded;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_scannerSession = [[MSScannerSession alloc] initWithScanner:[MSScanner sharedInstance]];
[_scannerSession setScanOptions:kMSScanOptions];
[_scannerSession setDelegate:self];
}
return self;
}
- (void)session:(MSScannerSession *)scanner didScan:(MSResult *)result {
if (!result) {
return;
}
[_scannerSession pause];
NSString *resultStr = nil;
if (result) {
switch ([result getType]) {
case MS_RESULT_TYPE_IMAGE:
resultStr = [NSString stringWithFormat:#"Immagine trovata: %#", [result getValue]];
break;
case MS_RESULT_TYPE_EAN8:
case MS_RESULT_TYPE_EAN13:
resultStr = [NSString stringWithFormat:#"EAN trovato: %#", [result getValue]];
break;
default:
break;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
UIActionSheet *asView = [[UIActionSheet alloc]initWithTitle:resultStr delegate:self cancelButtonTitle:#"OK" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
asView.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[asView showInView:self.view];
[self addObjectToList:resultStr];
});
}
- (void)addObjectToList:(NSString *)objectName {
// Ricerca dell'oggetto
NSString *object = [objectName substringFromIndex:18];
if ([object isEqualToString:#"Binario_con_coppia"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_colorati"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_rossi"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Bici_da_corsa"]) {
[self showAlert:object];
}
}
- (void)showAlert:(NSString*)name {
name = [name stringByReplacingOccurrencesOfString:#"_" withString:#" "];
nameOfObjectScanned = name;
NSString *message = [NSString stringWithFormat:#"Ho riconosciuto questo oggetto: %#, vuoi aggiungerlo al carrello?", name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:message delegate:self cancelButtonTitle:#"Aggiungi" otherButtonTitles:#"Annulla", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(#"Aggiungi");
for (int i = 0; i < [reader.objArray count]; i++) {
if ([[reader.objArray[i]objectForKey:#"name"] isEqualToString:nameOfObjectScanned]) {
// Salvo il nome dell'oggetto trovato, il prezzo e la descrizione
NSString *name = [reader.objArray[i]objectForKey:#"name"];
NSString *desc = [reader.objArray[i]objectForKey:#"desc"];
NSString *price = [reader.objArray[i]objectForKey:#"price"];
NSDictionary *newObjectAdded = [[NSDictionary alloc]init];
newObjectAdded = #{#"name": name,
#"desc": desc,
#"price": price};
[arrayObjectAdded addObject:newObjectAdded];
}
}
} else {
NSLog(#"Annulla");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
[_scannerSession resume];
}
- (void)viewDidLoad
{
[super viewDidLoad];
arrayObjectAdded = [[NSMutableArray alloc]init];
CALayer *videoPreviewLayer = [self.videoPreview layer];
[videoPreviewLayer setMasksToBounds:YES];
CALayer *captureLayer = [_scannerSession previewLayer];
[captureLayer setFrame:[self.videoPreview bounds]];
[videoPreviewLayer insertSublayer:captureLayer below:[[videoPreviewLayer sublayers] objectAtIndex:0]];
reader = [[XmlReader alloc]init];
[reader parseXml];
[_scannerSession startCapture];
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
}
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
- (void)dealloc {
[_scannerSession stopCapture];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)stopScanner:(id)sender {
ReportViewController *reportVC = [[ReportViewController alloc]initWithNibName:#"ReportViewController" bundle:nil];
reportVC.reportArray = arrayObjectAdded;
[reportVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:reportVC animated:YES completion:nil];
}
#end
To recognize picture I'm using this AR SDK. I hope you can help me to understand where's my issue
Your problem is that in viewDidLoad you have the code:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
this is the last thing you do in that method. So the instance of PaymentViewController that you create and set the delegate on is immediately destroyed (by ARC).
You need to modify your code so that you call setDelegate: on the actual instance of PaymentViewController that is presented on screen as this is the instance that needs to use the delegate (it receives the callback from the alert view).
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.
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.
I finally got my leaderboard to show up. Now I just need to implement that my score will pop up.
My score is saved as an NSString in NSUserDefaults under the name score.
Here is some code:
Game_CenterViewController.h
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
#import "GameCenterManager.h"
#class GameCenterManager;
#interface Game_CenterViewController : UIViewController <UIActionSheetDelegate, GKLeaderboardViewControllerDelegate, GKAchievementViewControllerDelegate, GameCenterManagerDelegate> {
GameCenterManager *gameCenterManager;
int64_t currentScore;
NSString *currentLeaderBoard;
}
#property (nonatomic, retain) GameCenterManager *gameCenterManager;
#property (nonatomic, assign) int64_t currentScore;
#property (nonatomic, retain) NSString* currentLeaderBoard;
#end
Game_CenterViewController.m
#import "Game_CenterViewController.h"
#import "AppSpecificValues.h"
#import "GameCenterManager.h"
#implementation Game_CenterViewController
#synthesize gameCenterManager;
#synthesize currentScore;
#synthesize currentLeaderBoard;
- (void)dealloc {
[gameCenterManager release];
[currentLeaderBoard release];
[currentScoreLabel release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.currentLeaderBoard = thescore101;
self.currentScore = score
if ([GameCenterManager isGameCenterAvailable]) {
self.gameCenterManager = [[[GameCenterManager alloc] init] autorelease];
[self.gameCenterManager setDelegate:self];
[self.gameCenterManager authenticateLocalUser];
} else {
// The current device does not support Game Center.
}
}
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController {
[self dismissModalViewControllerAnimated: YES];
[viewController release];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.gameCenterManager = nil;
self.currentLeaderBoard = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
The current score is where I'm trying to put the NSString in.
EDITED: I think it would be better to use int for the currentScore.
Is this what you are looking for?
- (void)submitMyScore:(int64_t)score
{
GKScore *myScoreValue = [[[GKScore alloc] initWithCategory:#"yourCat"] autorelease];
myScoreValue.value = (int)score;
[myScoreValue reportScoreWithCompletionHandler:^(NSError *error){
if(error != nil){
NSLog(#"Score Submission Failed");
} else {
NSLog(#"Score Submitted: %d",(int)score);
}
}];
}
So you should add a IBAction
- (IBAction)buttonPressed
{
[self submitMyScore:currentScore];
}
With this and connecting the SEND MY SCORE button to this IBAction, you will have your score submitted.
I hope this to be useful for you.