I try do get the locationServicesEnabled function to work... but my UIAlert shows up no matter if the locationServices is enabled or not! How do I get this to work properly?
#synthesize locationServicesEnabled
-(void)viewDidLoad {
[super viewDidLoad];
if(![CLLocationManager locationServicesEnabled]) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
} else {
[[[[UIAlertView alloc] initWithTitle:#"Location services."
message:#"Location services are disabled."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease] show];
}
}
Thank you in advance!
Looks like your condition is backwards. It currently says "if NOT location-services-enabled then start updating else alert".
Change the if to:
if([CLLocationManager locationServicesEnabled])
Remove the !.
Related
My Map application is on iTune market which runs good on iOS 4 and iOS 5. I have developed this application using Xcode 3.2, iPhone sdk 4.2 on Mac mini having Mac OS 10.6.8.
This application .ipa file is crashing after launching on iOS 6. I am developing app on MacMini and I could not able to run xcode 4.5 to rectify the crash. I am pasting some code which runs on launching. If there is some deprecated methods which causes crash then please help because I am not able to check this code without Mac OS 10.7(Lion)..
- (void)viewDidLoad {
if([appDelegate.markers count] == 0 && [mapView.annotations count] == 0 && UserId.data == 0)
{
[self performSelector:#selector(launchActivity) withObject:nil afterDelay:1.0];
}
}
- (void) launchActivity {
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"No Internet Connectivity!" message:#"This app require an internet connection via WiFi or cellular network to work." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
if([self.mapView.annotations count] == 1)
{
}
if (locationManager.location == nil)
{
}
else
{
// Change map region using span (degrees)...
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion region = MKCoordinateRegionMake
(locationManager.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
mapView.showsUserLocation = YES;
BOOL locationAllowed = [CLLocationManager locationServicesEnabled];
if (locationAllowed==NO)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location Service Disabled"
message:#"To re-enable, please go to Settings and turn on Location Service for this app."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
return;
}
else
{
[NSThread detachNewThreadSelector:#selector(updateFilterProgress) toTarget:self withObject:nil]; //NSthread not taken because Default.png stay while loading the results
//========================================================================================== ==================================
//Searching Showroom Locations withing the radius
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
appDelegate = (HettichLocatorAppDelegate *)[[UIApplication sharedApplication] delegate];
CLLocationCoordinate2D location;
NSString *url = [[NSString alloc] initWithFormat:#"http://www.company.com.au/directory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=5",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude];
radiusinurl.text = #"5km";
NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
[parser release];
[xmlParser release];
//[URL release];
[url release];
if(success)
{
annobjs = [[NSMutableArray array] retain];
if([appDelegate.markers count] == 0)
{
//some logic
}
else
{
for (int i = 0; i < [appDelegate.markers count]; i++)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
location.latitude = [aMarker.lat floatValue];
location.longitude =[aMarker.lng floatValue];
AddressAnnotation *annobj = [[AddressAnnotation alloc] initWithCoordinate:location];
annobj.title = aMarker.name;
annobj.subtitle = aMarker.address;
[annobjs addObject:annobj];
[mapView addAnnotation:annobj];
CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude}; //for zoom in the showroom results region
MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
mapView.region = ausRegion;
[annobj release];
[_tableView reloadData];
}
}
}
else
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"" message:#"Unable to find the results." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
[pool release];
}
}
}
}
I just started coding in Objective C, and am making an app that will track the users location, and send an alert with the latlng in it. This code isn't complete in the slightest, but I ran into a problem with trying to use the variable I created "lat" in the "viewDidLoad" for the alert. I declared the variable in the CLLocationManager delegate/method(I don't really know what it's called) and I don't know how to use it in other places.
- (void)viewDidLoad
{
locationManager =[[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 100.0f;
[locationManager startUpdatingLocation];
UIAlertView *message = [[UIAlertView alloc] initWithTitle: #"Your current Latitude is:"
message:This is where I want to put the variable "lat"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void) locationmanager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
{
NSString *lat = [[NSString alloc] initWithFormat: #"%g",newLocation.coordinate.latitude];
NSString *lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
}
Any help would be appreciated!
Simple solution.
Your ViewController .h should look something like this
#interface ViewController : UIViewController {
NSString *lat;
NSString *lng;
}
then this becomes
-(void) locationmanager: (CLLocationManager *) manager
didUpdateToLocation: (CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation
{
lat = [[NSString alloc] initWithFormat: #"%g",newLocation.coordinate.latitude];
lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
NSLog(lat);
NSLog(lng);
}
NSlog simple out puts to the console which is locate just below where you code
remove
UIAlertView *message = [[UIAlertView alloc] initWithTitle: #"Your current Latitude is:"
message:This is where I want to put the variable "lat"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
Because that will just show an alert as soon as the view is loaded
Hope this helps
I am creating an application in which I have add a facility for post message on ur account. Now this facility I am adding an event for scheduling. With help of that user can write a message and post that later or on particular date and time. For this I used a local notification event which is generate on given date by user. But problem is that when notification generate then I have call a function which is used for post message on Facebook. For generate notification I have used this code:
-(IBAction)save{
NSString *str1=[NSString stringWithFormat:#"%#",txt_date.text];
NSString *str2=[NSString stringWithFormat:#" %#",txt_time.text];
str1=[str1 stringByAppendingFormat:str2];
selected_label.text= str1;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *today=[NSDate date];
NSDateFormatter* formatter_current = [[[NSDateFormatter alloc] init] autorelease];
formatter_current.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
//Set the required date format
[formatter_current setDateFormat:#"yyyy-MM-dd hh:mm a"];
NSLog(#"current date is =%#",str1);
today=[formatter_current dateFromString:str1];
NSLog(#"current date:-%#",today);
UILocalNotification* ln = [[UILocalNotification alloc] init];
ln.alertBody = #"Wake Up Sid";
ln.applicationIconBadgeNumber = 1;
ln.fireDate = today; //[NSDate dateWithTimeIntervalSinceNow:15];
ln.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSLog(#"alarm will activate on%#",today);
NSDateFormatter* formatter_alarm = [[[NSDateFormatter alloc] init] autorelease];
NSLocale *uslocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[formatter_alarm setLocale:uslocale];
[uslocale release];
formatter_alarm.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[formatter_alarm setDateFormat:#"hh:mm a"];
NSString *str=[formatter_alarm stringFromDate:today];
NSLog(#"%#",str);
ln.alertBody = [NSString stringWithFormat:#"Your first appointment at %#",str];
ln.soundName = UILocalNotificationDefaultSoundName;
ln.repeatInterval=NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:ln];
[ln release];
}
and in appdelegate file I use this function for received notification and call post message function:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
// Override point for customization after application launch.
self.viewController=[[demo_social_updatesViewController alloc]initWithNibName:#"demo_social_updatesViewController" bundle:nil];
nav_controller=[[UINavigationController alloc] initWithRootViewController:self.viewController];
// Add the view controller's view to the window and display.
[self.window addSubview:nav_controller.view];
[self.window makeKeyAndVisible];
appDelegate_acess_token=[[NSUserDefaults standardUserDefaults] stringForKey:#"access_token"];
application.applicationIconBadgeNumber = 0;
// Handle launching from a notification
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
NSLog(#"Recieved Notification %#",localNotif);
}
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
if (application.applicationIconBadgeNumber == 1) {
BOOL tmp=[Global_Class_parsing post_comment_fb:appDelegate_acess_token uesr_comment:#"testing message111"];
if(tmp){
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"Sucessfully posted to photos & wall!"
message:#"Check out your Facebook to see!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av show];
}
else{
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"error"message:#"Check connection!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av show];
}
}
/*
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.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
/*
Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
*/
if (application.applicationIconBadgeNumber == 1) {
BOOL tmp=[Global_Class_parsing post_comment_fb:appDelegate_acess_token uesr_comment:#"testing message111"];
if(tmp){
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"Sucessfully posted to photos & wall!"
message:#"Check out your Facebook to see!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av show];
}
else{
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"error"message:#"Check connection!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av show];
}
}
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateInactive) {
NSLog(#"Recieved Notification %#",notification);
} else {
NSLog(#"Recieved Notification method call.");
}
}
Now problem is that when notification generate and applicationbadge number become 1 then it not call any function and my post message function not calling. So how I fix that error?
I get solution for this question is that i have two way to implement scheduling with post method one is simply use notification. And another is use web-service. I have used both and working well.
When i am using reverse geocoding in iphone i get this error in console.
/SourceCache/ProtocolBuffer_Sim/ProtocolBuffer-51.2/Runtime/PBRequester.m:684 server returned error: 503
What does it mean and how this error can be removed to get the geocoding information of current location? I have run this in both simulator and device and same error occurs from last two days. Few days back it gives the proper information.
I can solve this problem in following ways:
First in my interface,i use
MKReverseGeocoder *mkReverseGeocoder;
and in my implementation
CLLocation *currLocation;
currLocation = [locationManager location];
if(mkReverseGeocoder)
{
[mkReverseGeocoder autorelease];
}
mkReverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[currLocation coordinate]];
[mkReverseGeocoder setDelegate:self];
[mkReverseGeocoder start];
and use the delegate method
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
NSString *msg = [[NSString alloc] initWithFormat:#"%#",[[placemark addressDictionary] objectForKey:#"FormattedAddressLines"]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Details:" message:msg delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
[msg release];
}
After doing this I can get reverseGeocoding information.
I know from this forum that this is a known bug that has been reported to Apple, but I am concerned that the memory leak keeps increasing everytime I call the view.
the relevant code is
-(IBAction)getlocationgo:(id) sender{
//NSAutoreleasePool *pool;
//pool = [[NSAutoreleasePool alloc] init];
self.locationManager=[[[CLLocationManager alloc]init]autorelease];
self.locationManager.delegate = self;
[locationManager startUpdatingLocation];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//mapView.showsUserLocation =YES;
//[pool release];
}
- (void)locationManager:(CLLocationManager*)aManager didFailWithError:(NSError*)anError
{
switch([anError code])
{
case kCLErrorLocationUnknown: // location is currently unknown, but CL will keep trying
break;
case kCLErrorDenied: // CL access has been denied (eg, user declined location use)
{UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Location Error"
message:#"Please enable Location Services in the Settings menu"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
[alert show];
[alert release];}
break;
case kCLErrorNetwork: // general, network-related error
{UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Location Error"
message:#"The Little Helper can't find you - please check your network connection or that you are not in airplane mode"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
[alert show];
[alert release];}
break;
}
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"thisruns");
MKCoordinateSpan span;
span.latitudeDelta =0.2;
span.longitudeDelta =0.2;
MKCoordinateRegion region;
region.span = span;
region.center = newLocation.coordinate;
[mapView setRegion:region animated:YES];
mapView.showsUserLocation =YES;
mapView.mapType = MKMapTypeHybrid;
latitude.text = [NSString stringWithFormat:#"%f",newLocation.coordinate.latitude];
longitude.text = [NSString stringWithFormat:#"%f",newLocation.coordinate.longitude];
NSString *newloc=longitude.text;
NSLog(#"long%f", newloc);
[locationManager stopUpdatingLocation];
}
the property's are with this
#property (nonatomic, retain) CLLocationManager *locationManager;
and it is dealloced
mapView.delegate = nil;
[mapView release];
locationManager.delegate = nil;
[locationManager release];
I have been going back and forward with this for a few days now, any help or tips would be great.
Thank you
Edit One
Trying to access locationManager in the app delegate, everything runs but there is no update to the location from the IBaction
This is the code in the IBaction and the result from the log is (null)
LLHelperAppDelegate *appDelegate = (LLHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.locationManager startUpdatingLocation];
appDelegate.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
NSLog(#"%#", [appDelegate locationManager]);
Whilst as an Apple issue you won't be able to remove the leak entirely, you can definitely stop it from happening every time you trigger getlocationgo. Rather than constantly creating a CLLocationManager, just use a single CLLocationManager in your app's delegate (or create a singleton to support it). That way you'll only alloc/init a location manager once during your app's lifecycle, whereas currently you alloc/init one every time you reload that view / call the getlocationgo method.