How to trigger a video when a user reaches a certain location? - iphone

This is my CoreLocationController.h objective c class
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
extern const CLLocationAccuracy kCLLocationAccuracyBest;
#protocol CoreLocationControllerDelegate
#required
- (BOOL)startRegionMonitoring;
- (void)locationUpdate:(CLLocation *)location; // Our location updates are sent here
- (void)locationError:(NSError *)error; // Any errors are sent here
#end
#interface CoreLocationController : NSObject <CLLocationManagerDelegate, MKMapViewDelegate> {
CLLocationManager *locMgr;
CLLocationCoordinate2D coordinate;
IBOutlet MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
id delegate;
}
#property (nonatomic, retain) CLLocationManager *locMgr;
#property (nonatomic, assign) id delegate;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#end
and this is the CorelocationController.m
#import "CoreLocationController.h"
#implementation CoreLocationController
#synthesize locMgr, delegate, coordinate;
- (id)init {
self = [super init];
if(self != nil) {
self.locMgr = [[[CLLocationManager alloc] init] autorelease]; // Create new instance of locMgr
self.locMgr.delegate = self; // Set the delegate as self.
[locMgr setDistanceFilter:kCLDistanceFilterNone];
[locMgr setDesiredAccuracy:kCLLocationAccuracyBest];
[worldView setShowsUserLocation:YES];
}
return self;
}
- (BOOL)startRegionMonitoring {
if (![CLLocationManager regionMonitoringAvailable] || ![CLLocationManager regionMonitoringEnabled] )
return NO;
CLLocationCoordinate2D home;
home.latitude = +51.49410630;
home.longitude = -0.10251360;
CLRegion * region = [[CLRegion alloc] initCircularRegionWithCenter:home radius:10.0 identifier:#"home"];
if (locMgr == nil)
locMgr = ([[CLLocationManager alloc] init]);
[locMgr startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest];
[region release];
return YES;
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#"Enteed location");
// [self leavingHomeNotify];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location entered" message:#"Region entered" delegate:NULL cancelButtonTitle:#"OK" otherButtonTitles:NULL];
[alert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:#protocol(CoreLocationControllerDelegate)]) { // Check if the class assigning itself as the delegate conforms to our protocol. If not, the message will go nowhere. Not good.
[self.delegate locationUpdate:newLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if([self.delegate conformsToProtocol:#protocol(CoreLocationControllerDelegate)]) { // Check if the class assigning itself as the delegate conforms to our protocol. If not, the message will go nowhere. Not good.
[self.delegate locationError:error];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location failed" message:#"Location failed" delegate:NULL cancelButtonTitle:#"OK" otherButtonTitles:NULL];
[alert show];
}
- (void)dealloc {
[self.locMgr release];
[super dealloc];
}
#end
This is the CoreLocationDemoViewer.h
#import <UIKit/UIKit.h>
#import "CoreLocationController.h"
#import <MapKit/MapKit.h>
#interface CoreLocationDemoViewController : UIViewController <CoreLocationControllerDelegate, MKMapViewDelegate> {
CoreLocationController *CLController;
IBOutlet UILabel *locLabel;
MKMapView *worldView;
}
#property (nonatomic, retain) CoreLocationController *CLController;
#property (nonatomic, retain) IBOutlet UILabel *locLabel;
#property (nonatomic, retain) MKMapView *worldView;
#end
This is the CoreLocationDemoViewer.m
#import "CoreLocationDemoViewController.h"
#implementation CoreLocationDemoViewController
#synthesize CLController;
#synthesize locLabel;
#synthesize worldView;
- (void)viewDidLoad {
[super viewDidLoad];
self.worldView.mapType = MKMapTypeStandard; // also MKMapTypeSatellite or MKMapTypeHybrid
CLController = [[CoreLocationController alloc] init];
CLController.delegate = self;
[CLController.locMgr startUpdatingLocation];
worldView.zoomEnabled = YES;
worldView.scrollEnabled = YES;
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)u
{
CLLocationCoordinate2D loc = [u coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
- (void)locationUpdate:(CLLocation *)location {
locLabel.text = [location description];
// [mapView setCenterCoordinate:location.coordinate];
// [mapView setShowsUserLocation:YES];
CLLocationCoordinate2D coord = [location coordinate];
// Add it to the map view
// [worldView addAnnotation:mp];
// MKMapView retains its annotations, we can release
// [mp release];
// Zoom the region to this location
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 50, 50);
[worldView setRegion:region animated:YES];
// [locationManager stopUpdatingLocation];
}
- (void)locationError:(NSError *)error {
locLabel.text = [error description];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)viewDidUnload {
[super viewDidUnload];
self.worldView = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[CLController release];
[worldView release];
[super dealloc];
}
#end
Ok so this is what i want. Until now it shows a map with the user location
and it finds the exact location which is shown on a label.. correct if i am doing anything wrong..
What i want to do is trigger a video when a user reaches a certain location...
IAm approaching right?

I think if you are just having trouble getting the mapView to zoom correctly, use the MKCoordinate stuff from this post, How do I zoom an MKMapView.
I am working on a mapview as well that zooms to a decent level for viewing, and I am setting the lattitudeDelta and longitudeDelta for the map. Works good for me.

Perhaps something is wrong with setting the delegate? I usually specify the delegate in the .h file like this:
id <CoreLocationControllerDelegate> delegate;
and
#property (nonatomic, assign) id <CoreLocationControllerDelegate> delegate;
EDIT
Also, did you check that -mapView:didUpdateUserLocation: is being called?

I don't see you assigning the delegate for worldView (but you do for your other stuff). Try adding worldView.delegate = self; in your viewDidLoad.

Related

change location to coordinates and also call didUpdateUserLocation method

This is my implementation file :
#import "mapViewController.h"
#interface mapViewController ()
#end
#implementation mapViewController
#synthesize mapView,source,dest,latdest,latsource,longdest,longsource;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
dest=#"delhi";
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CLGeocoder *geocoder1 = [[CLGeocoder alloc] init];
[geocoder1 geocodeAddressString:source
completionHandler:^(NSArray* placemarks, NSError* error)
{
for (CLPlacemark* aPlacemark in placemarks)
{
CLLocationCoordinate2D coordinate;
coordinate.latitude = aPlacemark.location.coordinate.latitude;
latsource=&coordinate.latitude;
coordinate.longitude = aPlacemark.location.coordinate.longitude;
longsource=&coordinate.longitude;
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:(coordinate)];
[annotation setTitle:source];
annotation.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:annotation];
}
}];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region =MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
[self.view addSubview:self.mapView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This is my header file :
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface mapViewController : UIViewController <MKMapViewDelegate>
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property(strong,nonatomic) NSString *source,*dest;
#property(nonatomic) CLLocationDegrees *latsource,*longsource;
#property(nonatomic) CLLocationDegrees *latdest,*longdest;
#end
First i want to know why didUpdateUserLocation method is never called.I also want to know the code to add a destination whose coordinates are stored in latdest and longdest.Both of them will get their values from static variable "dest" which has the value "delhi" in it .My final aim is to trace a route on the map from source coordinates(latsource,longsource) to destination coordinates(latest,longdest).
I am new to ios development so i might have done some noob mistakes.
didUpdateUserLocation method won't be called if you not set mapView.delegate = self;
If you use a class, which has delegate methods, and you want to use them, everytime you should set its delegate = self
Don't use the same name as in delegates: mapView
in header:
#property (weak, nonatomic) IBOutlet MKMapView *myMapView;
be sure you connected the IBOutlet MKMapView *myMapView in IterfaceBuilder
in implementation file:
#synthesize myMapView;
in your - (void)viewDidLoad
myMapView.delegate = self;
you have to correct all self.mapView to myMapView
You made a really big mistake:
if you use IBOutlet you have to add on InterfaceBuilder , and connect it.
or you can create everything from code:
#property (weak, nonatomic) MKMapView *myMapView;
myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,320,480)];
then add the screen with
[self.view addSubview:myMapView];

Controls in a ViewController losing their state after memory warning while off screen

The situation is very similar to that described by this my other question, except that the delegation seems to work fine. I'm providing some more detail about my code. I'm just striping out non-relevant/trivial parts.
ReportScreen.h
#interface ReportScreen : UIViewController <UIImagePickerControllerDelegate, UITextViewDelegate, MBProgressHUDDelegate, SoapDelegate, MapLocationChoiceDelegate>
// ...
#property (nonatomic, retain) MKPointAnnotation *annotation;
#property (nonatomic, retain) IBOutlet UITextView *textView;
#property (nonatomic, retain) IBOutlet UIButton *cameraButton;
#property (nonatomic, retain) IBOutlet UIButton *libraryButton;
#property (nonatomic, retain) IBOutlet UIButton *locationButton;
#property (nonatomic, retain) IBOutlet UIButton *sendButton;
#end
ReportScreen.m
#implementation ReportScreen
#synthesize annotation;
#synthesize textView;
#synthesize cameraButton;
#synthesize libraryButton;
#synthesize locationButton;
#synthesize sendButton;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Here I used to store the VC's state to a file but it shouldn't be needed now that I'm assigning it as delegate and said delegate seems to still be there even after a memory warning.
}
- (void)viewDidLoad {
[super viewDidLoad];
placeholderText = #"Tell us what's wrong…";
textView.text = placeholderText;
self.annotation = nil;
[self isReadyToSubmit];
hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:hud];
hud.delegate = self;
hud.labelText = #"Invio in corso…";
hud.dimBackground = YES;
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Here I used to restore the state of the VC from file but… y'know.
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self isReadyToSubmit];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:#"goToMap"]) {
MapScreen *vc = (MapScreen *)segue.destinationViewController;
// HERE's the magic
vc.mapLocationChoiceDelegate = self;
// MAGIC ends
if(self.annotation != nil) {
vc.annotations = [[NSMutableArray alloc] init];
[vc.annotations addObject:self.annotation];
}
}
}
- (BOOL)isReadyToSubmit {
if(self.annotation != nil) {
locationButton.highlighted = YES;
}
if(![textView.text isEqualToString:placeholderText] && self.annotation != nil) {
[sendButton setEnabled:YES];
} else {
[sendButton setEnabled:NO];
}
return [sendButton isEnabled];
}
- (void)textViewDidBeginEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:placeholderText]) {
theTextView.text = #"";
}
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(didFinishEditing:)];
[self.navigationItem setRightBarButtonItem:done animated:YES];
}
- (void)textViewDidEndEditing:(UITextView *)theTextView {
if([theTextView.text isEqualToString:#""]) {
theTextView.text = placeholderText;
}
[self isReadyToSubmit];
}
- (void)didFinishEditing:(id)sender {
[self.navigationItem setRightBarButtonItem:nil animated:YES];
[self.textView resignFirstResponder];
}
// THIS is my delegate protocol's method
- (void)locationChosen:(MKPointAnnotation *)theAnnotation {
self.annotation = theAnnotation;
NSLog(#"R: %#", textView.text);
}
#end
MapScreen.h
#protocol MapLocationChoiceDelegate <NSObject>
- (void)locationChosen:(MKPointAnnotation *)annotation;
#end
// ---
#interface MapScreen : UIViewController <MKMapViewDelegate>
- (void)handleLongPress:(id)sender;
#property (nonatomic, retain) NSMutableArray *annotations;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property (weak) id<MapLocationChoiceDelegate> mapLocationChoiceDelegate;
#end
MapScreen.m
#implementation MapScreen
#synthesize annotations;
#synthesize mapView;
#synthesize mapLocationChoiceDelegate;
- (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.
}
- (void)viewDidLoad {
[super viewDidLoad];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0;
[self.mapView addGestureRecognizer:lpgr];
[mapView addAnnotations:self.annotations];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#pragma mark - Map handling
- (void)handleLongPress:(id)sender {
if(![sender isKindOfClass:[UILongPressGestureRecognizer class]]) {
return;
}
UILongPressGestureRecognizer *gr = (UILongPressGestureRecognizer *)sender;
if (gr.state != UIGestureRecognizerStateBegan) {
return;
}
CGPoint touchPoint = [gr locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = touchMapCoordinate;
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
for(id a in self.annotations) {
if(![a isKindOfClass:[MKUserLocation class]]) {
[mapView removeAnnotation:a];
}
}
[mapView addAnnotation:annotation];
self.annotations = [NSMutableArray arrayWithArray:[mapView annotations]];
// NSDictionary *userInfo = [NSDictionary dictionaryWithObject:annotation forKey:#"annotation"];
// [[NSNotificationCenter defaultCenter] postNotificationName:#"PositionChosen" object:nil userInfo:userInfo];
[self.mapLocationChoiceDelegate locationChosen:annotation];
NSLog(#"M: %#", ((ReportScreen *)self.mapLocationChoiceDelegate).textView.text);
}
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
if([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString *AnnotationIdentifier = #"Annotation";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (!pinView) {
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
} else {
pinView.annotation = annotation;
}
return pinView;
}
#end
The issue is:
ReportScreen pushes (performs segue to, actually) the MapScreen.
If I have some data in the UITextView or if I set some state to the buttons in the ReportScreen and I get a memory warning while the MapScreen is pushed, once I go back to the ReportScreen, all those fields don't show those settings. Apparently textView.text is still set, and so are the states of the buttons, they're just not shown.
Question: why?

"Program received signal "SIGABRT" when building a calculator

(I'm beginner.)
I'm practicing Navigation Controller. I try to implement a simple calculator.
I ran the code in simulator. After I pressed any button which was linked to "addFunction", "substractFunction", "multiplyFunction" or "divideFunction", It crashed.
The debugger marked the following code in main.m
int retVal = UIApplicationMain(argc, argv, nil, nil);
and said "Thread 1: Program received signal: "SIGABRT"."
Does anyone know how to cope with this situation? Thanks.
Here's the code:
ChangeAppView.h:
#import <UIKit/UIKit.h>
#class ChangeViewController;
#interface ChangeAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) UINavigationController *navigationController;
#end
ChangeAppDelegate.m:
#import "ChangeAppDelegate.h"
#import "ChangeViewController.h"
#implementation ChangeAppDelegate
#synthesize window;
#synthesize navigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
navigationController = [[UINavigationController alloc] init];
self.window.rootViewController = navigationController;
ChangeViewController *changeViewController = [[ChangeViewController alloc] initWithNibName:#"ChangeViewController" bundle:nil];
[navigationController pushViewController:changeViewController animated:YES];
[changeViewController release];
[self.window makeKeyAndVisible];
return YES;
}
…
- (void)dealloc
{
[navigationController release];
[window release];
[super dealloc];
}
#end
CalculatorViewController.h:
#import <UIKit/UIKit.h>
#interface CalculatorViewController : UIViewController
{
IBOutlet UITextField *numberField1;
IBOutlet UITextField *numberField2;
IBOutlet UILabel *resultLabel;
}
#property (nonatomic , retain) IBOutlet UITextField *numberField1;
#property (nonatomic , retain) IBOutlet UITextField *numberField2;
#property (nonatomic , retain) IBOutlet UILabel *resultLabel;
-(IBAction)addFunction:(id)sender;
-(IBAction)substractFunction:(id)sender;
-(IBAction)multiplyFunction:(id)sender;
-(IBAction)divideFunction:(id)sender;
-(IBAction)clear:(id)sender;
-(IBAction)backgroundTap:(id)sender;
#end
CalculatorViewController.m:
#import "CalculatorViewController.h"
#implementation CalculatorViewController
#synthesize numberField1;
#synthesize numberField2;
#synthesize resultLabel;
-(IBAction)addFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [NSString stringWithFormat:#"%2.f" , a+b];
}
-(IBAction)substractFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
NSString *result = [[NSString alloc] initWithFormat:#"%2.f" , a-b];
resultLabel.text = result;
[result release];
}
-(IBAction)multiplyFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.f" , a*b];
}
-(IBAction)divideFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.3f" , a/b];
}
-(IBAction)clear:(id)sender
{
numberField1.text = #"";
numberField2.text = #"";
resultLabel.text = #"";
}
-(IBAction)backgroundTap:(id)sender
{
[numberField1 resignFirstResponder];
[numberField2 resignFirstResponder];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[numberField1 release];
[numberField2 release];
[resultLabel 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)viewDidLoad
{
self.title = #"Calculator";
[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
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
From the exception above, it seems that your IBActions are not properly connected.
As dasdom mentioned, delete all your buttons, create new buttons and then add IBAction methods accordingly.
Also one more thing i recognized in your code, in the multiply and divide methods there is a memory leak.You have written
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.f" , a*b];
it should be
resultLabel.text = [[[NSString alloc] initWithFormat:#"%2.f" , a*b]autorelease];
or
resultLabel.text = [NSString StringWithFormat:#"%2.f" , a*b];
and do a similar change in divide method also.
To what did you link your backgroundtap method?
It seems that you buttons aren't buttons. They seem to be view. Delete the buttons from you nib and put new buttons there and link them you our IBActions.

Adding a 3rd button and have date picker for time

NEW CODE
DatePickerViewController.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewControllerDelegate;
#interface DatePickerViewController : UIViewController {
IBOutlet UIDatePicker *datePicker;
id<DatePickerViewControllerDelegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker;
#property (assign) id<DatePickerViewControllerDelegate> delegate;
NSInteger buttonPressed;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed:(id)sender;
#end
#protocol DatePickerViewControllerDelegate <NSObject>
#optional
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController.m
#import "DatePickerViewController.h"
#implementation DatePickerViewController
#synthesize datePicker, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker date]];
[self.delegate datePickerViewController:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker release];
[super dealloc];
}
#end
DatePickerViewController2.h
#import <UIKit/UIKit.h>
#protocol DatePickerViewController2Delegate;
#interface DatePickerViewController2 : UIViewController {
IBOutlet UIDatePicker *datePicker2;
id<DatePickerViewController2Delegate> delegate;
}
#property (retain) IBOutlet UIDatePicker *datePicker2;
#property (assign) id<DatePickerViewController2Delegate> delegate;
NSInteger buttonPressed2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
- (IBAction)doneButtonPressed2:(id)sender;
#end
#protocol DatePickerViewController2Delegate <NSObject>
#optional
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate;
#end
DatePickerViewController2.m
#import "DatePickerViewController2.h"
#implementation DatePickerViewController2
#synthesize datePicker2, delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
self.title = #"Date Picker2";
}
return self;
}
- (void)viewDidLoad {
NSLog(#"Date Picker2. viewDidLoad");
[super viewDidLoad];
double days = 2.0f;
datePicker2.date = [NSDate dateWithTimeIntervalSinceNow:60.0f * 60.0f * 24.0f * days];
}
//-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate;
- (IBAction)doneButtonPressed2:(id)sender
{
if ([self.delegate respondsToSelector:#selector(datePickerViewController2:didChooseDate:)]) {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:[datePicker2 date]];
[self.delegate datePickerViewController2:self didChooseDate:dateString];
[self dismissModalViewControllerAnimated:YES];
}
}
- (void)dealloc {
[datePicker2 release];
[super dealloc];
}
#end
DatePickerModalExampleAppDelegate.h
#import <UIKit/UIKit.h>
#class DatePickerModalExampleViewController;
#interface DatePickerModalExampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
DatePickerModalExampleViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet DatePickerModalExampleViewController *viewController;
#end
DatePickerModalExampleAppDelegate.m
#import "DatePickerModalExampleAppDelegate.h"
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
DatePickerModalExampleViewController.h
#import <UIKit/UIKit.h>
#import "DatePickerViewController.h"
#import "DatePickerViewController2.h"
#interface DatePickerModalExampleViewController : UIViewController <DatePickerViewControllerDelegate> {
IBOutlet UIButton *button;
IBOutlet UIButton *button2;
IBOutlet UIButton *button3;
}
#property(nonatomic, retain) IBOutlet UIButton *button;
#property(nonatomic, retain) IBOutlet UIButton *button2;
#property(nonatomic, retain) IBOutlet UIButton *button3;
-(IBAction)buttonPressed:(id)sender;
-(IBAction)buttonPressed2:(id)sender;
#end
DatePickerModalExampleViewController.m
#import "DatePickerModalExampleViewController.h"
#implementation DatePickerModalExampleViewController
#synthesize button;
#synthesize button2;
#synthesize button3;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
-(IBAction)buttonPressed:(id)sender{
NSLog(#"I was pressed");
buttonPressed = ((UIButton *)sender).tag;
DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
switch (((UIButton*)sender).tag)
{
case 100001:
NSLog(#"Button 1 was pressed");
//some code
break;
case 100002:
NSLog(#"Button 2 was pressed");
//some code
break;
}
}
-(IBAction)buttonPressed2:(id)sender{
NSLog(#"I was pressed2");
buttonPressed2 = ((UIButton *)sender).tag;
DatePickerViewController2 *datePickerViewController2 = [[DatePickerViewController2 alloc] initWithNibName:#"DatePickerViewController2" bundle:nil];
datePickerViewController2.delegate = self;
[self presentModalViewController:datePickerViewController2 animated:YES];
[datePickerViewController2 release];
switch (((UIButton*)sender).tag)
{
case 100003:
NSLog(#"Button 3 was pressed");
//some code
break;
}
}
-(void)viewDidLoad{
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
self.button3.tag = 100003;
buttonPressed = -1;
buttonPressed2 = -1;
}
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed];
buttonPressed = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
-(void)datePickerViewController2:(DatePickerViewController2 *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
if (buttonPressed2 == -1)
return;
UIButton *buttonToSet = (UIButton*)[self.view viewWithTag:buttonPressed2];
buttonPressed2 = -1;
[buttonToSet setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[button3 release];
[button2 release];
[button release];
[super dealloc];
}
#end
Hello you can set the property "tag" on button to identify it
Uncomment
- (void)viewDidLoad {
[super viewDidLoad];
}
And type :
- (void)viewDidLoad {
[super viewDidLoad];
self.button.tag = 100001;
self.button2.tag = 100002;
}
then
turn in DatePickerModalExampleViewController.h
(IBAction)buttonPressed to (IBAction)buttonPressed:(id)sender;
Then turn in DatePickerModalExampleViewController.m
-(IBAction)buttonPressed to -(IBAction)buttonPressed:(id)sender
and in DatePickerModalExampleViewController.m this method could be like that :
-(IBAction)buttonPressed:(id)sender
{
switch(((UIButton*)sender).tag)
{
case 100001
NSLog(#"Button 1 was pressed");
DatePickerViewController *datePickerViewController =[DatePickerViewController alloc] initWithNibName:#"DatePickerViewController" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
break;
case 100002 :
NSLog(#"Button 2 was pressed");
// some code
break;
}
}
As you use the interfacebuilder I'm not friend with it but you must relink your actions
I'm writting from my PC so without xcode some code can contains syntax error be carreful. but it's the main idea.
Use tag for both buttons and check the condition accordingly...

Camera Overview in iPhone for Augmented Reality App

Hey Guys I have the following simple Code :
WhereAmIViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface WhereAmIViewController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
CLLocation *startingPoint;
IBOutlet UILabel *latitudeLabel;
IBOutlet UILabel *longitudeLabel;
IBOutlet UILabel *magneticHeading;
}
#property (retain, nonatomic) CLLocationManager *locationManager;
#property (retain, nonatomic) CLLocation *startingPoint;
#property (retain, nonatomic) UILabel *latitudeLabel;
#property (retain, nonatomic) UILabel *longitudeLabel;
#property (nonatomic, retain) UILabel *magneticHeading;
#end
WhereAmIViewController.m
#import "WhereAmIViewController.h"
#implementation WhereAmIViewController
#synthesize locationManager;
#synthesize startingPoint;
#synthesize latitudeLabel;
#synthesize longitudeLabel;
#synthesize magneticHeading;
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
NSString *magneticstring = [[NSString alloc] initWithFormat:#"%0.0f°",
newHeading.magneticHeading];
magneticHeading.text = magneticstring;
[magneticstring release];
}
#pragma mark -
-(void)viewDidLoad
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (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.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[locationManager release];
[startingPoint release];
[latitudeLabel release];
[longitudeLabel release];
[super dealloc];
}
#pragma mark -
#pragma mark CLLocationManagerDelegate Methods
-(void)locationManager:(CLLocationManager *)manger
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if(startingPoint == nil)
self.startingPoint = newLocation;
NSString *latitudeString = [[NSString alloc] initWithFormat:#"%g",newLocation.coordinate.latitude];
latitudeLabel.text = latitudeString;
[latitudeString release];
NSString *longitudeString = [[NSString alloc] initWithFormat:#"%g",newLocation.coordinate.longitude];
longitudeLabel.text = longitudeString;
[longitudeString release];
}
-(void)longitudeManager:(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:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
#end
So that's what I am displaying on screen .. I just wanted to know how get these 3 labels as an overview for the camera . I have refered to http://www.musicalgeometry.com/archives/821
But having trouble as mine is "View Based app" and the tutorial uses a "Windows Based app" template .. How can I configure this code to get the camera overlay ?
P.S: The background color is : noColor (transparent ).
Thank You !
You need a UIImagePickerController, and then you create a UIView and add your 3 labels in appropriate locations in subview then you can call, picker.cameraOverlayView = YOUR_UI_VIEW and picker.showsCameraControls = NO. If you already set up everything inside your WhereAmIViewController then you can do picker.cameraOverlayView = whereAmIVC.view