Possible memory leak - iphone

I know this is a very stupid question to ask but i have a view controller which has a mapview in it and some uibuttons i have done every thng to eliminate all the leaks bt still after 2-3 toggle between two controller app crashs. Below is the code for allocation and dellocation. BTW i dont get any "did recive memoru warning".. Thnx alot
.h/
#interface MapView : BaseViewController <MKMapViewDelegate,MKAnnotation> {
MKMapView *mapView;
NSMutableArray *placeName;
NSString *mid;
UISegmentedControl *segmentedControl;
IBOutlet UILabel *numberofbeeps;
NSInteger badgenumber;
}
#property (nonatomic, retain) UILabel *numberofbeeps;
#property(nonatomic, retain) NSString *mid;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic,retain) NSMutableArray *placeName;
#property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
-(IBAction)refreshButtonPressed:(id)sender;
-(IBAction) segmentedControlIndexChanged;
-(IBAction)SignUpButtonPressed:(id)sender;
-(IBAction)BackButtonPressed:(id)sender;
-(IBAction)AddBeepButtonPressed:(id)sender;
-(id)initWithAnnotation:(id ) annotation;
-(IBAction)sliderChanged:(id)sender;
-(IBAction)MyAccountPageButtonPressed:(id)sender;
-(IBAction)MyBeepsButtonPressed:(id)sender;
#end
.m/
-(void)network:(WNetwork*)network didFinishLoadingWithRequest:(NSInteger)pReq data:(NSMutableDictionary*)pData
{
[self removeLoader];
switch (pReq) {
case JBJsonParser:
{
NSMutableArray *array = [NSMutableArray new];
self.placeName = array;
[array release];
self.placeName = pData;
badgenumber = [placeName count];
NSString *checkstring = [[AppHelper mDataManager] objectForKey:#"numberofbeepsnearby"];
NSInteger check = [checkstring intValue];
switch (check) {
case 0:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"No beeps found nearby. Why not beep something?"];
NSLog(#"%#",checkstring);
}
break;
case 1:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beep found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
default:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beeps found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
}
if ([placeName count])
{
for (int i =0; i < [placeName count]; i++)
{
NSDictionary *dict = [placeName objectAtIndex:i];
CLLocationCoordinate2D coordinatemain;
coordinatemain.latitude = [[dict objectForKey:#"Lat"] doubleValue];
coordinatemain.longitude = [[dict objectForKey:#"long"] doubleValue];
DLog(#"id of Beeps %#", mid);
NSString *username = [NSString stringWithFormat:#"by %#",[dict objectForKey:#"username"]];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = [dict objectForKey:#"beep"];
ann.subtitle = username;
ann.beepid=[dict objectForKey:#"beepid"];
ann.coordinate = coordinatemain;
ann.coordinate.latitude == [[dict objectForKey:#"Lat"] doubleValue];
ann.coordinate.longitude == [[dict objectForKey:#"long"] doubleValue];
[mapView addAnnotation:ann];
[ann release];
}
}
}
break;
default:
break;
}
}
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
case 1:
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark request delegates
-(void)makeAccomodationRequest
{
NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
[self.mWNetowrk makeRequsetWithURL:URL_Showbeepsmap type:JBJsonParser paramDictionary:paramDic delegate:self];
[paramDic autorelease];
}
-(BOOL)network:(WNetwork*)network shouldStartForRequest:(NSInteger)pReq
{
[self addLoaderWithtext:#"Loading"];
return YES;
}
-(void)network:(WNetwork*)network didFailForRequest:(NSInteger)pReq WithError:(NSString*)error
{
[AppHelper showAlert:error];
[self removeLoader];
}
-(void)initializeView
{
[self initializeOutlets];
[self makeAccomodationRequest];
}
-(void)initializeOutlets
{
}
-(IBAction)BackButtonPressed:(id)sender
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)refreshButtonPressed:(id)sender
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)MyAccountPageButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
{
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyAccountPage *objCont = [[MyAccountPage alloc] initWithNibName:#"MyAccountPage" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
}
-(IBAction)MyBeepsButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
//NSString *sessionStr = [session stringValue];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"MyBeeps" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyBeeps1 *objCont = [[MyBeeps1 alloc] initWithNibName:#"MyBeeps1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
-(IBAction)AddBeepButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
Check20M *objCont = [[Check20M alloc] initWithNibName:#"Check20M" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
#pragma mark -
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation) {
// NSLog(#"nil");
return nil; }
MKPinAnnotationView *pinView = nil;
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.frame=CGRectMake(0, 0, 30, 30);
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
MyAnnotation *temp = (MyAnnotation*)annotation;
infoButton.tag = [temp.beepid integerValue];
[infoButton addTarget:self action:#selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = infoButton;
[defaultPinID release];
return pinView;
}
-(IBAction)showDetails:(id)sender{
UIButton *button = (UIButton*)sender ;
NSLog(#"Annotation Click");
BeepsDetail *objCont = [[BeepsDetail alloc] initWithNibName:#"BeepsDetail" bundle:nil];
objCont.mId = [NSString stringWithFormat:#"%d",button.tag];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
#pragma mark -
#pragma mark mapView delegates
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
[self initializeView];
mapView.showsUserLocation = YES;
[self makeAccomodationRequest];
CLLocation *location = [[AppHelper appDelegate] mLatestLocation];
MKCoordinateRegion region;
region.center.latitude = location.coordinate.latitude;
region.center.longitude = location.coordinate.longitude;
region.span.latitudeDelta = 0.001;
// Add a little extra space on the sides
region.span.longitudeDelta = 0.001;
// Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
// Listen to change in the userLocation
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.mapView = nil;
self.numberofbeeps =nil;
self.mapView = nil;
self.segmentedControl = nil;
}
- (void)dealloc
{
[mapView release];
// [self.mapView removeFromSuperview];
[placeName release];
//[mid autorelease];
[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.
}
#end

The following only works on the simulator not on device...
Here is a good procedure for finding bad access errors using zombies. All the tools are built into Xcode.
First change to profiling. Click and hold one the run button.
Now choose zombies. This tool warns you just before you are about to use a deallocated object which would other wise trigger a bad access.
Now when a zombie is detected you will see something like this (minus annotatios!) using the tools you can see the object lifecycle. Double click to be taken the the code.
Hope it helps someone!

I would suggest declaring modal view controllers (objCont) as autorelease as opposed to manually releasing them.

Related

(MKAnnotationView *) mapView: not firing on first view

-(MKAnnotationView *) mapView: is not firing on the first run of the view.
I load pins in from a JSON call. The pins load fine with all the information but the call out(*see code) and turning them purple.(done in the -(MKAnnotationView *) mapView2:) however when I leave that tab and go back to it then it gets called and all is well.
Why this in not OK? Because end-users will not know that the map pins have a call out with phone call capabilities if they only check once.
Progress Flow: it loads the map. Loads the Pins. Changes the pins to purple with the call out. Then Zooms to pins and current location. But on the first run it does not Change the pins with call out.
I have narrowed it down to -(MKAnnotationView *) mapView: not firing the first time on several tests however on one test it did fire but only was called on the second of two pins till the view was reloaded.
I am open to any suggestions to improve any of the code weather it pertains to this or not. I always love learning better ways to do what I have done. So feel free with your criticisms.
.h file
#class Reachability;
#interface LocationsViewController : UIViewController <MKMapViewDelegate,CLLocationManagerDelegate>
{
NSString *phone;
IBOutlet MKMapView *mapView;
CLLocationManager *locationManager;
NSURLConnection *theConnection;
Reachability* internetReachable;
Reachability* hostReachable;
}
#property(nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic, retain)CLLocationManager *locationManager;
#property(nonatomic, retain) NSString *phone;
- (BOOL) connectedToNetwork;
- (void) mapPinsJSON;
#end
.m file
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
MapAnnotation *ann1;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (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
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
MKCoordinateRegion region;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
NSTimer *myTimer;
myTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(countDown) userInfo:nil repeats:NO];
[self zoomMapViewToFitAnnotations:self.mapView animated:YES];
}
-(void)countDown{
[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[mapView removeAnnotations:mapView.annotations];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[self performSelectorInBackground:#selector(mapPinsJSON) withObject:nil];
}
}
- (void) mapPinsJSON{
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/api/newlocations25/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (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 YES;
}
#define MINIMUM_ZOOM_ARC 0.014 //approximately 1 miles (1 degree of arc ~= 69 miles)
#define ANNOTATION_REGION_PAD_FACTOR 1.15
#define MAX_DEGREES_ARC 360
- (void)zoomMapViewToFitAnnotations:(MKMapView *)mapView3 animated:(BOOL)animated
{
NSArray *annotations = mapView.annotations;
int count = [mapView.annotations count];
if ( count == 0) { return; } //bail if no annotations
//convert NSArray of id <MKAnnotation> into an MKCoordinateRegion that can be used to set the map size
//can't use NSArray with MKMapPoint because MKMapPoint is not an id
MKMapPoint points[count]; //C array of MKMapPoint struct
for( int i=0; i<count; i++ ) //load points C array by converting coordinates to points
{
CLLocationCoordinate2D coordinate = [(id <MKAnnotation>)[annotations objectAtIndex:i] coordinate];
points[i] = MKMapPointForCoordinate(coordinate);
}
//create MKMapRect from array of MKMapPoint
MKMapRect mapRect = [[MKPolygon polygonWithPoints:points count:count] boundingMapRect];
//convert MKCoordinateRegion from MKMapRect
MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
//add padding so pins aren't scrunched on the edges
region.span.latitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;
region.span.longitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;
//but padding can't be bigger than the world
if( region.span.latitudeDelta > MAX_DEGREES_ARC ) { region.span.latitudeDelta = MAX_DEGREES_ARC; }
if( region.span.longitudeDelta > MAX_DEGREES_ARC ){ region.span.longitudeDelta = MAX_DEGREES_ARC; }
//and don't zoom in stupid-close on small samples
if( region.span.latitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.latitudeDelta = MINIMUM_ZOOM_ARC; }
if( region.span.longitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.longitudeDelta = MINIMUM_ZOOM_ARC; }
//and if there is a sample of 1 we want the max zoom-in instead of max zoom-out
if( count == 1 )
{
region.span.latitudeDelta = MINIMUM_ZOOM_ARC;
region.span.longitudeDelta = MINIMUM_ZOOM_ARC;
}
[mapView3 setRegion:region animated:animated];
}
#end
Well I feel sheepish. Here is what fixed it for me.
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
}

How do I set map zoom based on nearest pin to current location

Right now I am setting my region based on users current location. I would like to now set the zoom level so I can see the users current location and the nearest pin that is being pulled in via json.
Not until run time will the app know the number of pins or the locations of said pins.
Here is what I have so far.
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (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
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"New latitude: %f", newLocation.coordinate.latitude);
NSLog(#"New longitude: %f", newLocation.coordinate.longitude);
MKCoordinateRegion region;
region.center.latitude =newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
//[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[mapView removeAnnotations:mapView.annotations];
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I did something similar, but based on two annotations, not the user's location. You should be able to replace mapView.centerCoordinate with mapView.userLocation.coordinate.
in viewForAnnotation:
CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
Note, this code will re-calc the zoom level each time you add an annotation. You may need to save the distance and only change the map if the new distance is greater than the prior distance.

AlAssetsLibrary issue, code works in 4.3 but not 5.0

Here's my issue, if I access this class with iOS 4.X, the code works fine.... however whenever I try to access it with iOS 5.0, I get nil values for the groups & assets. What's the best way to get this to work? I'm posting the entire class for a reference...
.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "DejViewController.h"
#class Event, Venue;
#interface SelectMediaViewController : DejViewController <UITableViewDelegate, UITableViewDataSource> {
Event *event;
Venue *venue;
UITableView *tableView;
NSMutableArray *selectedAssets;
NSMutableArray *allMedia;
ALAssetsLibrary *library;
NSMutableArray *assetGroups;
}
#property (nonatomic, retain) Event *event;
#property (nonatomic, retain) Venue *venue;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *allMedia;
#property (nonatomic, retain) NSMutableArray *assetGroups;
- (IBAction)continuePressed:(id)sender;
#end
.m
#import <ImageIO/ImageIO.h>
#import "SelectMediaViewController.h"
#import "CaptionAllMediaViewController.h"
#import "MediaItem.h"
#import "CLValueButton.h"
#import "SelectMediaTableViewCell.h"
#define kMediaGridSize 75
#define kMediaGridPadding 4
#define kSelectImageTag 828
#interface SelectMediaViewController(Private)
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset;
- (void)loadData;
#end
#implementation SelectMediaViewController
#synthesize event, venue;
#synthesize tableView;
#synthesize allMedia,assetGroups;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
selectedAssets = [[NSMutableArray alloc] init];
showNextButton = YES;
}
return self;
}
- (void)dealloc {
[tableView release];
[event release];
[venue release];
[library release];
[allMedia release];
[selectedAssets release];
[assetGroups 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 {
[super viewDidLoad];
NSLog(#"SelectMediaViewController - viewDidLoad");
}
- (void)viewDidUnload {
NSLog(#"SelectMediaViewController - viewDidUnload");
[self setTableView:nil];
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidAppear");
[super viewDidAppear:animated];
[self setNavTitle:#"Select Media"];
[self loadData];
[self.tableView reloadData];
float contentOffset = self.tableView.contentSize.height - self.tableView.frame.size.height;
if (contentOffset < 0) contentOffset = 0;
[self.tableView setContentOffset:CGPointMake(0, contentOffset) animated:NO];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"SelectMediaViewController - viewDidDisappear");
self.allMedia = nil;
[selectedAssets removeAllObjects];
[self.tableView reloadData];
}
- (void)loadData {
NSMutableArray *tempArray = [[NSMutableArray array] init];
library = [[ALAssetsLibrary alloc] init];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
NSLog(#"See Asset: %#", result);
[tempArray addObject:result];
NSLog(#"assets count: %i", tempArray.count);
}
else {
NSLog(#"result nil or end of list");
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
[group enumerateAssetsUsingBlock:assetEnumerator];
NSLog(#"group: %#",group);
}
else {
NSLog(#"group nil or end of list");
}
if (stop) {
self.allMedia = [NSMutableArray arrayWithCapacity:[tempArray count]];
self.allMedia = tempArray;
NSLog(#"Loaded data: %d & %d", [tempArray count], [self.allMedia count]);
}
};
//ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
}];
//[library release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)continuePressed:(id)sender {
if ([selectedAssets count] > 0) {
CaptionAllMediaViewController *captionVC = [[CaptionAllMediaViewController alloc] initWithNibName:nil bundle:nil];
captionVC.event = self.event;
captionVC.venue = self.venue;
// Create media items
NSMutableArray *mediaItems = [NSMutableArray arrayWithCapacity:[selectedAssets count]];
for (ALAsset *asset in selectedAssets) {
MediaItem *item = [[MediaItem alloc] init];
item.asset = asset;
NSDictionary *metadata = [[asset defaultRepresentation] metadata];
NSDictionary *gpsMeta = [metadata objectForKey:#"{GPS}"];
if (gpsMeta) {
float latitude = [[gpsMeta objectForKey:#"Latitude"] floatValue];
if ([[gpsMeta objectForKey:#"LatitudeRef"] isEqualToString:#"S"]) latitude = latitude * -1;
float longitude = [[gpsMeta objectForKey:#"Longitude"] floatValue];
if ([[gpsMeta objectForKey:#"LongitudeRef"] isEqualToString:#"W"]) longitude = longitude * -1;
item.location = CLLocationCoordinate2DMake(latitude, longitude);
}
[mediaItems addObject:item];
[item release];
}
captionVC.media = mediaItems;
[self.navigationController pushViewController:captionVC animated:YES];
[captionVC release];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Images Selected"
message:#"Please select at least one image to continue."
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (void)imagePressed:(CLValueButton *)sender {
BOOL currentlySelected = [selectedAssets containsObject:sender.valueObject];
UIImageView *imageView = (UIImageView *)[sender viewWithTag:kSelectImageTag];
if (!currentlySelected) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
[selectedAssets addObject:sender.valueObject];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
[selectedAssets removeObject:sender.valueObject];
}
}
#pragma Table view methods
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Getting table view count: %d", [self.allMedia count]);
if ([self.allMedia count] == 0) return 0;
return ceil([self.allMedia count] / 4.0);
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 83;
NSLog(#"return83");
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SelectMediaTableViewCell *cell = (SelectMediaTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:#"MEDIA_CELL"];
if (!cell) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"SelectMediaTableViewCell" owner:nil options:nil] objectAtIndex:0];
// wire up selectors
[cell.image1 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image2 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image3 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.image4 addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
}
int startIndex = indexPath.row * 4;
for (int i = 0; i < 4; i++) {
ALAsset *thisAsset = (startIndex + i) < [self.allMedia count] ? [self.allMedia objectAtIndex:startIndex + i] : nil;
CLValueButton *button = nil;
switch (i) {
case 0:
button = cell.image1;
break;
case 1:
button = cell.image2;
break;
case 2:
button = cell.image3;
break;
case 3:
button = cell.image4;
break;
default:
break;
}
[self setContentForButton:button withAsset:thisAsset];
UIImageView *imageView = (UIImageView *)[button viewWithTag:kSelectImageTag];
// letse see if it's selected or not...
if ([selectedAssets containsObject:button.valueObject]) {
[imageView setImage:[UIImage imageNamed:#"image-select-active.png"]];
} else {
[imageView setImage:[UIImage imageNamed:#"image-select.png"]];
}
}
return cell;
}
- (void)setContentForButton:(CLValueButton *)button withAsset:(ALAsset *)asset {
button.hidden = asset == nil;
if (asset) {
CGImageRef image = [asset thumbnail];
[button setImage:[UIImage imageWithCGImage:image] forState:UIControlStateNormal];
}
[button setValueObject:asset];
}
#pragma -
#end
Any help would be much appreciated, I've been trying to figure this out for 3 days...
The ALAssetsLibrary page in the online documentation now says "The lifetimes of objects you get back from a library instance are tied to the lifetime of the library instance."

Three20 to save images?(Close)

i'm a new iPhone application developer,i need create one application like photo gallery.Now my problem is i donno how to save a image to photo album.
i have build my project is no error no werning to me.in my simulator can run the project.
But i cnt see any things i add.Hope can help me.Thanks.
my code here.
Three20PhotoDemoAppDelegate.h
#import <UIKit/UIKit.h>
#interface Three20PhotoDemoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
Three20PhotoDemoAppDelegate.m
#import "Three20PhotoDemoAppDelegate.h"
#import "AlbumController.h"
#import <Three20/Three20.h>
#implementation Three20PhotoDemoAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
TTNavigator* navigator = [TTNavigator navigator];
TTURLMap* map = navigator.URLMap;
[map from:#"demo://album" toViewController: [AlbumController class]];
[navigator openURLAction:[TTURLAction actionWithURLPath:#"demo://album"]];
return YES;
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)URL {
[[TTNavigator navigator] openURLAction:[TTURLAction actionWithURLPath:URL.absoluteString]];
return YES;
}
- (void)dealloc {
[super dealloc];
}
#end
PhotoSource.h
#import <Three20/Three20.h>
#import <Three20/Three20+Additions.h>
typedef enum {
PhotoSourceNormal = 0,
PhotoSourceDelayed = 1,
PhotoSourceVariableCount = 2,
PhotoSourceLoadError = 4,
} PhotoSourceType;
#interface PhotoSource : TTURLRequestModel <TTPhotoSource> {
PhotoSourceType _type;
NSString* _title;
NSMutableArray* _photos;
NSArray* _tempPhotos;
NSTimer* _fakeLoadTimer;
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title
photos:(NSArray*)photos photos2:(NSArray*)photos2;
#end
PhotoSource.m
import "PhotoSource.h"
#implementation PhotoSource
#synthesize title = _title;
- (void)fakeLoadReady {
_fakeLoadTimer = nil;
if (_type & PhotoSourceLoadError) {
[_delegates makeObjectsPerformSelector: #selector(model:didFailLoadWithError:)
withObject: self
withObject: nil];
} else {
NSMutableArray* newPhotos = [NSMutableArray array];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
[newPhotos addObject:photo];
}
}
[newPhotos addObjectsFromArray:_tempPhotos];
TT_RELEASE_SAFELY(_tempPhotos);
[_photos release];
_photos = [newPhotos retain];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
[_delegates makeObjectsPerformSelector:#selector(modelDidFinishLoad:) withObject:self];
}
}
- (id)initWithType:(PhotoSourceType)type title:(NSString*)title photos:(NSArray*)photos
photos2:(NSArray*)photos2 {
if (self = [super init]) {
_type = type;
_title = [title copy];
_photos = photos2 ? [photos mutableCopy] : [[NSMutableArray alloc] init];
_tempPhotos = photos2 ? [photos2 retain] : [photos retain];
_fakeLoadTimer = nil;
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
photo.photoSource = self;
photo.index = i;
}
}
if (!(_type & PhotoSourceDelayed || photos2)) {
[self performSelector:#selector(fakeLoadReady)];
}
}
return self;
}
- (id)init {
return [self initWithType:PhotoSourceNormal title:nil photos:nil photos2:nil];
}
- (void)dealloc {
[_fakeLoadTimer invalidate];
TT_RELEASE_SAFELY(_photos);
TT_RELEASE_SAFELY(_tempPhotos);
TT_RELEASE_SAFELY(_title);
[super dealloc];
}
- (BOOL)isLoading {
return !!_fakeLoadTimer;
}
- (BOOL)isLoaded {
return !!_photos;
}
- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
if (cachePolicy & TTURLRequestCachePolicyNetwork) {
[_delegates makeObjectsPerformSelector:#selector(modelDidStartLoad:) withObject:self];
TT_RELEASE_SAFELY(_photos);
_fakeLoadTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(fakeLoadReady) userInfo:nil repeats:NO];
}
}
- (void)cancel {
[_fakeLoadTimer invalidate];
_fakeLoadTimer = nil;
}
- (NSInteger)numberOfPhotos {
if (_tempPhotos) {
return _photos.count + (_type & PhotoSourceVariableCount ? 0 : _tempPhotos.count);
} else {
return _photos.count;
}
}
- (NSInteger)maxPhotoIndex {
return _photos.count-1;
}
- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
if (photoIndex < _photos.count) {
id photo = [_photos objectAtIndex:photoIndex];
if (photo == [NSNull null]) {
return nil;
} else {
return photo;
}
} else {
return nil;
}
}
#end
Photo.h
#import <Three20/Three20.h>
#interface Photo : NSObject <TTPhoto> {
id<TTPhotoSource> _photoSource;
NSString* _thumbURL;
NSString* _smallURL;
NSString* _URL;
CGSize _size;
NSInteger _index;
NSString* _caption;
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption;
#end
Photo.m
#import "Photo.h"
#implementation Photo
#synthesize photoSource = _photoSource, size = _size, index = _index, caption = _caption;
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size {
return [self initWithURL:URL smallURL:smallURL size:size caption:nil];
}
- (id)initWithURL:(NSString*)URL smallURL:(NSString*)smallURL size:(CGSize)size
caption:(NSString*)caption {
if (self = [super init]) {
_photoSource = nil;
_URL = [URL copy];
_smallURL = [smallURL copy];
_thumbURL = [smallURL copy];
_size = size;
_caption;
_index = NSIntegerMax;
}
return self;
}
- (void)dealloc {
TT_RELEASE_SAFELY(_URL);
TT_RELEASE_SAFELY(_smallURL);
TT_RELEASE_SAFELY(_thumbURL);
TT_RELEASE_SAFELY(_caption);
[super dealloc];
}
- (void)viewDidLoad {
}
- (NSString*)URLForVersion:(TTPhotoVersion)version {
if (version == TTPhotoVersionLarge) {
return _URL;
} else if (version == TTPhotoVersionMedium) {
return _URL;
} else if (version == TTPhotoVersionSmall) {
return _smallURL;
} else if (version == TTPhotoVersionThumbnail) {
return _thumbURL;
} else {
return nil;
}
}
#end
AlbumController.h
#import <Three20/Three20.h>
#interface AlbumController : TTPhotoViewController <UIActionSheetDelegate>{
NSArray *images;
UIBarButtonItem *_clickActionItem;
UIToolbar *_toolbar;
}
#property (nonatomic, retain) NSArray *images;
#property (nonatomic, retain) UIBarButtonItem *_clickActionItem;
#property (nonatomic, retain) UIToolbar *_toolbar;
#end
AlbumController.m
#import "AlbumController.h"
#import "PhotoSource.h"
#import "Photo.h"
#implementation AlbumController
#synthesize images;
- (void)loadView {
CGRect screenFrame = [UIScreen mainScreen].bounds;
self.view = [[[UIView alloc] initWithFrame:screenFrame]
autorelease];
CGRect innerFrame = CGRectMake(0, 0,
screenFrame.size.width,
screenFrame.size.height);
_innerView = [[UIView alloc] initWithFrame:innerFrame];
_innerView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[self.view addSubview:_innerView];
_scrollView = [[TTScrollView alloc] initWithFrame:screenFrame];
_scrollView.delegate = self;
_scrollView.dataSource = self;
_scrollView.backgroundColor = [UIColor blackColor];
_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight;
[_innerView addSubview:_scrollView];
UIBarButtonItem *_actionButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/imageAction.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(popupActionSheet)];
_nextButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/nextIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(nextAction)];
_previousButton = [[UIBarButtonItem alloc] initWithImage:
TTIMAGE(#"bundle://Three20.bundle/images/previousIcon.png")
style:UIBarButtonItemStylePlain target:self action:#selector
(previousAction)];
UIBarButtonItem* playButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemPlay target:self action:#selector
(playAction)] autorelease];
playButton.tag = 1;
UIBarItem* space = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:
UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
autorelease];
_toolbar = [[UIToolbar alloc] initWithFrame:
CGRectMake(0, screenFrame.size.height - TT_ROW_HEIGHT,
screenFrame.size.width, TT_ROW_HEIGHT)];
_toolbar.barStyle = self.navigationBarStyle;
_toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleTopMargin;
_toolbar.items = [NSArray arrayWithObjects:
_actionButton, space, _previousButton, space,
_nextButton, space, nil];
[_innerView addSubview:_toolbar];
}
//(Just to add an action sheet)
//At the bottom of that codefile -- I added:
-(void)popupActionSheet {
UIActionSheet *popupQuery = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Save Image",nil];
popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[popupQuery showInView:self.view];
[popupQuery release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:
(int)buttonIndex {
//UIImage* image = [[TTURLCache sharedCache] imageForURL:imageURL];
if (buttonIndex==0){
UIImage* thisImage = [[TTURLCache sharedCache] imageForURL:
[_centerPhoto URLForVersion:TTPhotoVersionLarge]];
UIImageWriteToSavedPhotosAlbum(thisImage, nil, nil, nil);
//{UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"URL"
//message:[_centerPhoto URLForVersion:TTPhotoVersionLarge] delegate:self cancelButtonTitle:#"No" ,otherButtonTitles:#"Yes", nil];
//[alert show];}
}
}
-(void)createPhotos {
images = [[NSArray alloc] initWithObjects:
[[[Photo alloc] initWithURL:#"bundle://14.png" smallURL:#"bundle://14.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://30.png" smallURL:#"bundle://30.png"
size:CGSizeMake(320, 212)] autorelease],
[[[Photo alloc] initWithURL:#"bundle://back.jpeg" smallURL:#"bundle://back.jpeg"
size:CGSizeMake(319, 317)] autorelease],
nil];
}
- (void)viewDidLoad {
//[self loadView];
[self createPhotos]; // method to set up the photos array
self.photoSource = [[PhotoSource alloc]
initWithType:PhotoSourceNormal
title:#"SexyGirl"
photos:images
photos2:nil
];
}
#end
If all you need is to save an image to the Photos album, you can use:
UIImage *myImage;
UIImageWriteToSavedPhotosAlbum(myImage,nil,nil,nil);
If this is not your problem, then I don't get it. If you don't tell us where the problem is, posting three pages worth of code is pretty useless.

Need to get current location and destination location pin

How do I get the current location with green pin and destination location with red pin?
When I work on some stuff I get only destination location with red pin, not at the current location.
My source code.
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import <CoreLocation/CoreLocation.h>
#interface AddressAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
// CLLocationManager *locationManager;
// CLLocation *currentLocation;
}
#end
#interface MapViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate> {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
NSString *address;
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
#property(nonatomic,retain)CLLocation *currentLocation;
#property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
#end
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return #"Event";
}
- (NSString *)title{
//return #"Title";
return #"Allure-Exclusive";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES;
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title=#"Map-View";
// [self addressLocation];
[self showAddress];
NSLog(#"address is %#",address);
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.5;
span.longitudeDelta=0.5;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(#"locationString %#",locationString);
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];
NSLog(#"listItems %#",[listItems objectAtIndex:2]);
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation) {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
//
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (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 {
// [self stop];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[super dealloc];
}
#end
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation)
{
mapView.userLocation.title=#"Current Location";
[mapView setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
return nil;
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
When I changed the method. it's pointing blue and blinking,but it was pointing at different location, which is at infinite Loop mariani Ave location.
It was running this in a simulator.
You'll want to set showsUserLocation.
mapView.showsUserLocation = YES;