I want to detecting user's current location in my app.I am using objective c.It's working fine in simulator but while testing on device below error comes.
didFailWithError: Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)"
Please Help me to solve this issue.I am using Lat long value for find out place mark in my application.
if(version<8.0)
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
else
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[locationManager requestWhenInUseAuthorization];
}
[locationManager startUpdatingLocation];
}
Here are delegate method
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *placemark_str = [placemark locality];
subAdminArea.text=placemark.subAdministrativeArea;
NSString *are_str = [placemark subLocality];
subAdminArea.text=placemark.subAdministrativeArea;
NSString *location_str=[NSString stringWithFormat:#"%#,%#",are_str,placemark_str];
[[NSUserDefaults standardUserDefaults]setValue:location_str forKey:#"Location"];
NSLog(#"place mark str: %#",placemark_str);
}];
}}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(#"%#", [locations lastObject]);
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation: [locations lastObject] completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *placemark_str = [placemark locality];
NSString *are_str = [placemark subLocality];
NSString *location_str=[NSString stringWithFormat:#"%#,%#",are_str,placemark_str];
[[NSUserDefaults standardUserDefaults]setValue:location_str forKey:#"Location"];
}];}
- (void)requestAlwaysAuthorization{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView show];
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
[locationManager requestAlwaysAuthorization];
}}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}}
I have also update my plist file with NSLocationAlwaysUsageDescription->String & NSLocationWhenInUseUsageDescription -> String.
Thank You.
1) check that you actually have a valid WiFi and 3G connection
if you do then
2) go to settings and reset your location services
3) then reset your network settings
Related
I am developing an app to search nearest beacon device but not able to calling any delegate, Already I have beacons available but not finding any beacons.
Also I did not understand NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:#"3863C90B-1BA6-4A4E-ADD2-D64FF1286898"]; is static is passed or not?
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:#"3863C90B-1BA6-4A4E-ADD2-D64FF1286898"];
self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
identifier:#"com.jss.myidentifire"];
self.myBeaconRegion.notifyOnEntry = YES;
[self.locationManager startMonitoringForRegion:self.myBeaconRegion];
[self.locationManager startUpdatingHeading];
[self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion];
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
{
[locationManager requestStateForRegion:region];
}
-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
if (state == CLRegionStateInside)
{
[self locationManager:locationManager didEnterRegion:region];
}
}
- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion *)region
{
// We entered a region, now start looking for our target beacons!
self.statusLabel.text = #"Finding beacons.";
[self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"BeaconDetail" message:#"DidEnterRegion Called" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}
-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion *)region
{
// Exited the region
self.statusLabel.text = #"None found.";
[self.locationManager stopRangingBeaconsInRegion:self.myBeaconRegion];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"BeaconDetail" message:#"didExitRegion Called" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}
-(void)locationManager:(CLLocationManager*)manager
didRangeBeacons:(NSArray*)beacons
inRegion:(CLBeaconRegion*)region
{
self.statusLabel.text = #"Beacon found!";
CLBeacon *foundBeacon = [beacons firstObject];
NSString *uuid = foundBeacon.proximityUUID.UUIDString;
NSString *major = [NSString stringWithFormat:#"%#", foundBeacon.major];
NSString *minor = [NSString stringWithFormat:#"%#", foundBeacon.minor];
NSString *accuracy = [NSString stringWithFormat:#"%f", foundBeacon.accuracy];
accuracy = [NSString stringWithFormat:#"%f", foundBeacon.accuracy];
if (foundBeacon.proximity == CLProximityUnknown) {
self.distanceLabel.text = #"Unknown Proximity";
} else if (foundBeacon.proximity == CLProximityImmediate) {
self.distanceLabel.text = #"Immediate";
} else if (foundBeacon.proximity == CLProximityNear) {
self.distanceLabel.text = #"Near";
} else if (foundBeacon.proximity == CLProximityFar) {
self.distanceLabel.text = #"Far";
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:uuid forKey:#"uuid"];
[dict setObject:major forKey:#"major"];
[dict setObject:minor forKey:#"minor"];
[dict setObject:accuracy forKey:#"accuracy"];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"BeaconDetail" message:[NSString stringWithFormat:#"%#",dict] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}
Make sure you have obtained permission to scan for beacons by adding the following:
if([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
For the above to work, you also need to add a new key to your Info.plist file: NSLocationAlwaysUsageDescription with a value set to something like "This app wants to scan for beacons"
if you start the receiver when it's already in the beacon range, it's not going to fire. Just checking that you're walking far away from the beacon and then walking back into range to get it to fire?
I have methods in viewDidLoad, and it seems like the order of methods getting called is weird.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
// Retrieve Data
[self retrieveData];
}
After viewDidLoad is called, it calls the retrieveData method before locationManager.
Shouldn't the locationManager be called before retrieveData because of the order?
I am new in Objective C, thank you for your help in advance.
as per your need call your method in inside the delegate methods, so remove the [self retrieveData]; from ViewDidLoad and add into inside the didFailWithError or didUpdateLocations methods.
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.geocoder = [[CLGeocoder alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
// call here
[self retrieveData];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// set or stop your location update
manager = nil;
[self.locationManager stopUpdatingLocation];
[manager stopUpdatingLocation];
CLLocation *newLocation = locations[[locations count] -1];
CLLocation *currentLocation = newLocation;
NSString *longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
if (currentLocation != nil) {
NSLog(#"latitude: %#", latitude);
NSLog(#"longitude: #"%#", longitude);
}else {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
}
// call here
[self retrieveData];
}
Note
objective -C is the interpreter , it execute the every in step by step , so or may be your [self retrieveData]; is called in main thread, that is the reason it execute in prior.
Hi i am beginner in Ios and in my project i am using CLLocationManager for getting current location but when i turn off "Wifi" and i Enable the GPS service but current location is not displaying with out internet it's showing error message how can we get current location using GPs with out internet (i am using i pad for testing this app)
my code is below:
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]){
NSUInteger code = [CLLocationManager authorizationStatus];
if (code == kCLAuthorizationStatusNotDetermined && ([locationManager respondsToSelector:#selector(requestAlwaysAuthorization)] || [locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])) {
if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationAlwaysUsageDescription"]){
[locationManager requestAlwaysAuthorization];
[locationManager setDistanceFilter:10.0f];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
}
else if([[NSBundle mainBundle] objectForInfoDictionaryKey:#"NSLocationWhenInUseUsageDescription"]) {
[locationManager requestWhenInUseAuthorization];
[locationManager setDistanceFilter:10.0f];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
} else {
NSLog(#"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
}
}
}
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
adressLabel.text = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
}
else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
Add a line in the app's info.plist file, that says: NSLocationWhenInUseUsageDescription, it should fix your problem.
I am trying to make my app find a user's location in an address-like form (located after the "Reverse Geocoding" comment). Below is my code:
- (IBAction)getuserlocation:(id) sender{
//Getting Location
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSLog(address);
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
address = [NSString stringWithFormat:#"%# %#\n%# %#\n%#\n%#",
placemark.subThoroughfare, placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
My issue is that the compiler only prints out "(null)". (The line where I do this is located in the "getuserlocation" IBAction.) I'm not sure why this is. I've tested the app on an actual iPhone 6 Plus, which unlike the simulator, has access to location services.
If anyone would be able to point out where the error/problem in my code is, causing it to print out null, I would greatly appreciate it. Thanks in advance to all who reply.
***BTW: The following lines are in my viewDidLoad section:
locationManager = [[CLLocationManager alloc] init];
geocoder = [[CLGeocoder alloc] init];
You are logging address long before you get a location and convert it to an address.
Move the NSLog(address); to just after where you actually assign a value to address.
BTW - it should be more like: NSLog(#"Address: %#, address);.
Current location is not being found on initial load or resume after multi-tasking. This is what I have:
ViewController.h
#interface ViewController : UIViewController <CLLocationManagerDelegate, ADBannerViewDelegate, BEMSimpleLineGraphDelegate>
ViewController.m
#interface ViewController (){
CLLocationManager *locationManager;
CLLocation *location;
CLLocationCoordinate2D coordinate;
int timeofday;
NSString *cityName;
NSMutableArray *ArrayOfValues;
}
#end
Further down:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateLabels) name:UIApplicationWillEnterForegroundNotification object:nil];
// set up coordinates for current location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = (id)self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
location = [locationManager location];
}
Then my update labels method (which has other code that updates my view below this):
- (void)updateLabels
{
CLLocationCoordinate2D currentLocation = [location coordinate];
if (currentLocation.latitude) {
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
CLPlacemark *placemark = [placemarks objectAtIndex:0];
cityName = [NSString stringWithFormat:#"%# is currently",placemark.locality];
}];
[self updateLabels];
} else {
NSLog(#"Could not find the location.");
}
}
And here are the 2 delegate methods for cclocationmanager:
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
[self updateLabels];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error){
NSLog(#"Geocode failed with error: %#", error);
return;
}
// CLPlacemark *placemark = [placemarks objectAtIndex:0];
}];
}
Try removing the call to stopUpdatingLocation. Also un-comment the log statement in didUpdateToLocation.
Be aware that the method locationManager:didUpdateToLocation:fromLocation: is deprecated in iOS 6. It might not even be called in iOS 7. You should be using `locationManager:didUpdateLocations:' instead.
Your call to updateLabels is using the value set in the member variable location. However your didUpdateToLocation method is not setting this value.
Put some breakpoints in your code and see where it triggers.
Note, for a weather application you do not need kCLLocationAccuracyBest, that takes way more time than coarser settings. You'll get your answer much quicker.
You are setting location, which I assume is a class level iVar, in ViewDidLoad.
location = [locationManager location];
I expect that the location manager at that point has no location.
Then, in the delegate call, you are updating a method level iVar :
CLLocation *currentLocation = newLocation;
This variable is never used, that I can see. Your updateLabels call once again refers to location which has never been updated.
CLLocationCoordinate2D currentLocation = [location coordinate];
Change the delegate to:
location = newLocation;
As #Duncan C stated, the delegate method you are using is deprecated, you should really be using locationManager:didUpdateLocations: in which case you would use:
location = [locations lastObject];