How to find the current location address? - objective-c

I done the task on Mapkit to find the currentLocation by using below code. Now I want to display the current location address at the annotation pain.How to cal the geo coding method for displaying the current location address.latitude and longitude values?
#import "MapKitViewController.h"
#import "ViewController.h"
#define METERS_MILE 1609.344
#define METERS_FEET 3.28084
#interface MapKitViewController ()<CLLocationManagerDelegate,MKMapViewDelegate >
#end
#implementation MapKitViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// _mapView.delegate = self;
locationManager =[[CLLocationManager alloc] init];
[[self mapView ] setShowsUserLocation:YES];
[locationManager setDelegate:self];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
NSLog(#" startUpdatingLocation");
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *location=locations.lastObject;
[[self latitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.latitude]];
[[self longnitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.longitude]];
// [[self altitudeValue] setText:[NSString stringWithFormat:#"%.2f feet",location.altitude*METERS_FEET]];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2*METERS_MILE, 2*METERS_MILE);
[[self mapView] setRegion:viewRegion animated:YES];
MKPointAnnotation *point=[[MKPointAnnotation alloc]init];
point.coordinate=location.coordinate;
[self.mapView addAnnotation:point];
point.title=#"this is my place";
NSLog(#"I got the point");
NSLog(#"didUpdateLocations");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end

For display current location on map use this..
MKPointAnnotation *annonation = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D mycordinate;
mycordinate.latitude = [self.strlog floatValue];
mycordinate.longitude =[self.strlat floatValue];
annonation.coordinate = mycordinate;
[self.mapview addAnnotation:annonation];

Related

Objective C - Have only one pin at a time?

I have 2 different set of pins on top of a map view. One pin appears first and it's the user location, then when you search for a location in the search bar multiple pins appear depending on the location. I want to have one pin showing at a time. Once you search for the location the user's location pin should disappear, and once you select one of the multiple pins you searched the others should disappear.
Here's my code:
#import "UbicacionVC.h"
#import "SWRevealViewController.h"
#import <MapKit/Mapkit.h>
#import "Location.h"
#interface UbicacionVC ()
#end
#implementation UbicacionVC
#synthesize mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self inicializarComponentes];
self.mapView.delegate = self;
self.searchBar.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)inicializarComponentes {
[self.btnContinuar.layer setCornerRadius:20.0f];
[self.btnCancelar.layer setCornerRadius:20.0f];
////
UITapGestureRecognizer *gestureMenu = [[UITapGestureRecognizer alloc] init];
[gestureMenu addTarget:self.revealViewController action:#selector(revealToggle:)];
[gestureMenu setCancelsTouchesInView:NO];
[self.btnLeftMenu addGestureRecognizer:gestureMenu];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
////
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self->locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(#"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(#"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
CLLocationDegrees lat = newLocation.coordinate.latitude;
CLLocationDegrees lon = newLocation.coordinate.longitude;
CLLocation * location = [[CLLocation alloc]initWithLatitude:lat longitude:lon];
self.viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500);
[self.mapView setRegion:self.viewRegion];
}
-(void)localSearch:(NSString*)searchString{
[self.mapView setRegion:self.viewRegion];
MKLocalSearchRequest * request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = [searchString lowercaseString];
request.region = self.viewRegion;
MKLocalSearch* search = [[MKLocalSearch alloc] initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if([response.mapItems count] == 0){
NSLog(#"No matches \n");
}
else{
for(MKMapItem * item in response.mapItems){
Location * pin = [[Location alloc] initWith:item.placemark.title andSubtitle:item.phoneNumber andCoordinate:item.placemark.coordinate andImageName:#"" andURL:item.url.absoluteString];
[self.mapView addAnnotation:pin];
}
}
}];
}
#pragma mark UISearchBarDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[searchBar resignFirstResponder];
[self.mapView removeAnnotations:[self.mapView annotations]];
[self localSearch:searchBar.text];
}
#pragma mark MKMapViewDelegate
-(MKAnnotationView*)mapView:(MKMapView*)sender viewForAnnotation: (id<MKAnnotation>)annotation{
static NSString* identifier = #"reusablePin";
MKAnnotationView * aView = [sender dequeueReusableAnnotationViewWithIdentifier:identifier];
if(!aView){
aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
aView.canShowCallout = YES;
}
aView.annotation = annotation;
return aView;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%#",view.annotation.title);
NSLog(#"%#",view.annotation.subtitle);
}
I want to have one pin showing at a time.
How about break; in for loop?
for(MKMapItem * item in response.mapItems){
Location * pin = [[Location alloc] initWith:item.placemark.title andSubtitle:item.phoneNumber andCoordinate:item.placemark.coordinate andImageName:#"" andURL:item.url.absoluteString];
[self.mapView addAnnotation:pin];
// one pin showed
break;
}
Once you search for the location the user's location pin should disappear,
and once you select one of the multiple pins you searched the others should disappear.
You can use didSelectAnnotationView method.
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
// once you select one of the multiple pins, the others should disappear.
for (MKPointAnnotation *annotation in mapView.annotations) {
if (view.annotation != annotation) {
[mapView removeAnnotation:annotation];
NSLog(#"yes!!");
}
}
}

Append Google Maps URL with Current Location

I am trying to compose an email with a Google Maps link using Core Location and MessageUI. Presently my code produces this string: https://maps.google.com?saddr=Current+Location&daddr=0.000000,0.000000.
I would like to append the device's longitude and latitude with the URL.
Here is my implementation:
#import "ViewController.h"
#interface ViewController () <CLLocationManagerDelegate>
#end
#implementation ViewController{
NSString *currentLongitude;
NSString *currentLatitude;
NSString *googleMapsURL;
CLLocationManager *locationManager_;
}
- (void)viewDidLoad {
[super viewDidLoad];
locationManager_ = [[CLLocationManager alloc] init];
locationManager_.delegate = self;
locationManager_.distanceFilter = kCLDistanceFilterNone;
locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager_ requestAlwaysAuthorization];
[locationManager_ startUpdatingLocation];
}
- (IBAction)composeMailButton:(id)sender {
NSString *bodyHeader = #"Here are you directions:";
NSString *mailBody = [NSString stringWithFormat:#"%#\n%#", bodyHeader, googleMapsURL];
MFMailComposeViewController *emailComposer = [[MFMailComposeViewController alloc] init];
[emailComposer setSubject:#"Google Maps Directions"];
[emailComposer setMessageBody:mailBody isHTML:NO];
[emailComposer setToRecipients:#[#"castro.michael87#gmail.com"]];
[emailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self presentViewController:emailComposer animated:YES completion:nil];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
NSString *googleMapsURL = [[NSString alloc] initWithFormat:#"https://maps.google.com?saddr=Current+Location&daddr=%1.6f,%1.6f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
I am guessing that I have not correctly implemented the locationManager. Any input is very much appreciated!
First, you need to make use that you added the NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in your info.plist file.
Second, your viewController need to implement the <CLLocationManagerDelegate>
#interface ViewController ()<CLLocationManagerDelegate>
Third, setup your locationManager in your viewDidLoad method.
locationManager_ = [[CLLocationManager alloc] init];
locationManager_.delegate = self;
locationManager_.distanceFilter = kCLDistanceFilterNone;
locationManager_.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager_ requestAlwaysAuthorization];
[locationManager_ startUpdatingLocation];
Fourth, implement the -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations method:
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
NSString *googleMapsURL = [[NSString alloc] initWithFormat:#"https://maps.google.com?saddr=Current+Location&daddr=%1.6f,%1.6f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSLog(#"%#", googleMapsURL);
}
Finally, if you test in simulator, you need to simulate a location:
Code Snippet: https://gist.github.com/ziyang0621/b1be760596da54873f81

iOS 8 Map Kit Obj-C Cannot Get Users Location

I am working with Map Kit in iOS 8 using Obj-C NOT SWIFT. I cannot get the device location it is set a 0.00, 0.00 and I am getting the error:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
I have implemented: ( I have tried only one at a time and no luck )
if(IS_OS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
And in info.plist
NSLocationWhenInUseUsageDescription : App would like to use your location.
NSLocationAlwaysUsageDescription : App would like to use your location.
I do get prompted to allow the app to use my location but after I agree nothing changes. The location is being showed as 0.00, 0.00.
Code for displaying users location:
//Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
Mike.
**EDIT: View Answer Below.
I got it working. I've posted my code below to help anyone else having issues.
Here is my full code to get the MapKit Map View working in iOS 8.
In your AppName-Info.plist
Add a new row with the key name being:
NSLocationWhenInUseUsageDescription
Or
NSLocationAlwaysUsageDescription
With the value being a string of the message that you want to be displayed:
YourAppName would like to use your location.
In your header file. (I use App Name-Prefix.pch but YourViewController.h will work too)
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
YourViewController.h
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#interface YourViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> {
}
#property(nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic, retain) CLLocationManager *locationManager;
YourViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
mapView.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];
mapView.showsUserLocation = YES;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
NSLog(#"%#", [self deviceLocation]);
//View Area
MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
return [NSString stringWithFormat:#"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
- (NSString *)deviceLat {
return [NSString stringWithFormat:#"%f", self.locationManager.location.coordinate.latitude];
}
- (NSString *)deviceLon {
return [NSString stringWithFormat:#"%f", self.locationManager.location.coordinate.longitude];
}
- (NSString *)deviceAlt {
return [NSString stringWithFormat:#"%f", self.locationManager.location.altitude];
}
Enjoy!
--Mike
It's not written anywhere, but if your app starts with MapKit, you will still receive the error message "Trying to start MapKit location updates without prompting for location authorization" even after implementing MBarton's answer. To avoid it, you have to create a new view controller before the MapKit, and implement the location manager delegates there. I called it AuthorizationController.
So, in AuthorizationController.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MCIAuthorizationController : UIViewController <CLLocationManagerDelegate>
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
And in AuthorizationController.m:
- (void)viewDidLoad {
[super viewDidLoad];
// Location manager
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
}
#pragma mark - Location Manager delegates
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog(#"didUpdateLocations: %#", [locations lastObject]);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"Location manager error: %#", error.localizedDescription);
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.locationManager startUpdatingLocation];
[self performSegueWithIdentifier:#"startSegue" sender:self];
} else if (status == kCLAuthorizationStatusDenied) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location services not authorized"
message:#"This app needs you to authorize locations services to work."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else
NSLog(#"Wrong location status");
}
Try This One:
(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
self.mapView.showsUserLocation = YES;
}
Your code looks fine, though you do not need to call requestWhenInUseAuthorization and the other requestAlwaysAuthorization , choose one you need.
Code for displaying locations is just yet allocating locationManager, do not expect to get location data instantly.
you need to wait till delegate method gets called :
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
, then self.locationManager.location will also be set.
Further to Mikes answer, I found that using both [self.locationManager requestWhenInUseAuthorization]; and [self.locationManager requestAlwaysAuthorization]; as demonstrated in his code does not work. You should only use ONE.
I assume some further changes were made with a more recent/stable version of the API.
I had the same problem but adding these two line in plist file solved my problems
NSLocationWhenInUseUsageDescription
And
NSLocationAlwaysUsageDescription
NOTE : Must provide string description of both these values. You can use any of them in your controller file as below
self.locationManager= [[CLLocationManager alloc] init];
self.locationManager.delegate=self;
[self.locationManager requestAlwaysAuthorization];
You must implement CLLOcationManagerDelegate in your controller to access this functionality
To extend the accepted answer and if you create a sample project with just the above functionality, then apart from CoreLocation and Mapkit frameworks, you might need to add UIKit, Foundation and CoreGraphics framework manually as well in Xcode 6.
Actually, I am studying the CS193P Lecture 16, which is about location and map view, and I could not make the location manager work in iOS 8, applying what was in the video.
Looking at your answer, I could make it work.
The Info.plist was modified as described in the answers (I use the NSLocationWhenInUseUsageDescription).
In AddPhotoViewController.hn the define was added :
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
In AddPhotoViewController.m, the following code was added in ViewDidLoad (after self.image):
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER)
{
[self.locationManager requestWhenInUseAuthorization];
}
#endif
The authorization will be asked only once, the first time you launch the application.
The following was also added to AddPhotoViewController.h because it was not said in Lecture 16 :
#property (nonatomic) NSInteger locationErrorCode;
shouldPerformSegueWithIdentifier was modified to include else if (!self.location) :
else if (![self.titleTextField.text length])
{
[self alert:#"Title required"];
return NO;
}
else if (!self.location)
{
switch (self.locationErrorCode)
{
case kCLErrorLocationUnknown:
[self alert:#"Couldn't figure out where this photo was taken (yet)."]; break;
case kCLErrorDenied:
[self alert:#"Location Services disabled under Privacy in Settings application."]; break;
case kCLErrorNetwork:
[self alert:#"Can't figure out where this photo is being taken. Verify your connection to the network."]; break;
default:
[self alert:#"Cant figure out where this photo is being taken, sorry."]; break;
}
return NO;
}
else
{ // should check imageURL too to be sure we could write the file
return YES;
}
didFailWithError was added :
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
self.locationErrorCode = error.code;
}

Geofencing in Xcode 4, didEnterRegion gives multiple callbacks

I'm trying to create an app in Xcode 4 based on geofencing. The app will notify the user when entering a region with certain center coordinates and a certain radius given in meters. All my regions are saved in a p-list. However I get multiple callbacks and more locations than I want gets called (i.e. locations not even in the right location gets called. Below you can see our code. I have also added a kml-layer which you can ignore because it has nothing to do with the fencing. My p-list is an array and contains of 20 items with the type dictionary and the keys are title, latitude, longitude and radius. The radius is set to 50 meters.
ViewController.h
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#implementation ViewController
#synthesize coordinateLabel;
#synthesize mapView;
CLLocationManager *_locationManager;
NSArray *_regionArray;
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeMap];
[self initializeLocationManager];
NSArray *geofences = [self buildGeofenceData];
[self initializeRegionMonitoring:geofences];
[self initializeLocationUpdates];
}
- (void)viewDidUnload
{
[self setCoordinateLabel:nil];
[self setMapView:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)initializeMap {
CLLocationCoordinate2D initialCoordinate;
initialCoordinate.latitude = 41.88072;
initialCoordinate.longitude = -87.67429;
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(initialCoordinate, 400, 400) animated:YES];
self.mapView.centerCoordinate = initialCoordinate;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
- (void)initializeLocationManager {
// Check to ensure location services are enabled
if(![CLLocationManager locationServicesEnabled]) {
[self showAlertWithMessage:#"You need to enable location services to use this app."];
return;
}
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
}
- (void) initializeRegionMonitoring:(NSArray*)geofences {
if (_locationManager == nil) {
[NSException raise:#"Location Manager Not Initialized" format:#"You must initialize location manager first."];
}
if(![CLLocationManager regionMonitoringAvailable]) {
[self showAlertWithMessage:#"This app requires region monitoring features which are unavailable on this device."];
return;
}
for(CLRegion *geofence in geofences) {
[_locationManager startMonitoringForRegion:geofence];
}
}
- (NSArray*) buildGeofenceData {
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"regions" ofType:#"plist"];
_regionArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *geofences = [NSMutableArray array];
for(NSDictionary *regionDict in _regionArray) {
CLRegion *region = [self mapDictionaryToRegion:regionDict];
[geofences addObject:region];
}
return [NSArray arrayWithArray:geofences];
}
- (CLRegion*)mapDictionaryToRegion:(NSDictionary*)dictionary {
NSString *title = [dictionary valueForKey:#"title"];
CLLocationDegrees latitude = [[dictionary valueForKey:#"latitude"] doubleValue];
CLLocationDegrees longitude =[[dictionary valueForKey:#"longitude"] doubleValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
CLLocationDistance regionRadius = [[dictionary valueForKey:#"radius"] doubleValue];
return [[CLRegion alloc] initCircularRegionWithCenter:centerCoordinate
radius:regionRadius
identifier:title];
}
- (void)initializeLocationUpdates {
[_locationManager startUpdatingLocation];
}
#pragma mark - Location Manager - Region Task Methods
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(#"Entered Region - %#", region.identifier);
[self showRegionAlert:#"Entering Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"Exited Region - %#", region.identifier);
[self showRegionAlert:#"Exiting Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Started monitoring %# region", region.identifier);
}
#pragma mark - Location Manager - Standard Task Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.coordinateLabel.text = [NSString stringWithFormat:#"%f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
#pragma mark - Alert Methods
- (void) showRegionAlert:(NSString *)alertText forRegion:(NSString *)regionIdentifier {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:alertText
message:regionIdentifier
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
- (void)showAlertWithMessage:(NSString*)alertText {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Location Services Error"
message:alertText
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
#end
ViewController.m
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#implementation ViewController
#synthesize coordinateLabel;
#synthesize mapView;
#synthesize kmlParser;
CLLocationManager *_locationManager;
NSArray *_regionArray;
- (void)viewDidLoad
{
[super viewDidLoad];
[self initializeMap];
[self initializeLocationManager];
NSArray *geofences = [self buildGeofenceData];
[self initializeRegionMonitoring:geofences];
[self initializeLocationUpdates];
// Locate the path to the route.kml file in the application's bundle
// and parse it with the KMLParser.
NSString *path = [[NSBundle mainBundle] pathForResource:#"urbanPOIsthlm" ofType:#"kml"];
NSURL *url = [NSURL fileURLWithPath:path];
kmlParser = [[KMLParser alloc] initWithURL:url];
[kmlParser parseKML];
// Add all of the MKOverlay objects parsed from the KML file to the map.
NSArray *overlays = [kmlParser overlays];
[mapView addOverlays:overlays];
// Add all of the MKAnnotation objects parsed from the KML file to the map.
NSArray *annotations = [kmlParser points];
[mapView addAnnotations:annotations];
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
if (MKMapRectIsNull(flyTo)) {
flyTo = [overlay boundingMapRect];
} else {
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
for (id <MKAnnotation> annotation in annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
// Position the map so that all overlays and annotations are visible on screen.
mapView.visibleMapRect = flyTo;
}
- (void)viewDidUnload
{
[self setCoordinateLabel:nil];
[self setMapView:nil];
//DERAS alltså KML!!!
[kmlParser release];
///
[super viewDidUnload];
}
/////Deras alltså KML!!!
#pragma mark MKMapViewDelegate
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kmlParser viewForOverlay:overlay];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
return [kmlParser viewForAnnotation:annotation];
}
//////////
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)initializeMap {
CLLocationCoordinate2D initialCoordinate;
initialCoordinate.latitude = 59.3353733;
initialCoordinate.longitude = 18.0712647;
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(initialCoordinate, 400, 400) animated:YES];
self.mapView.centerCoordinate = initialCoordinate;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
- (void)initializeLocationManager {
// Check to ensure location services are enabled
if(![CLLocationManager locationServicesEnabled]) {
[self showAlertWithMessage:#"You need to enable location services to use this app."];
return;
}
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
}
- (void) initializeRegionMonitoring:(NSArray*)geofences {
if (_locationManager == nil) {
[NSException raise:#"Location Manager Not Initialized" format:#"You must initialize location manager first."];
}
if(![CLLocationManager regionMonitoringAvailable]) {
[self showAlertWithMessage:#"This app requires region monitoring features which are unavailable on this device."];
return;
}
for(CLRegion *geofence in geofences) {
[_locationManager startMonitoringForRegion:geofence
desiredAccuracy:kCLLocationAccuracyBest];
}
}
- (NSArray*) buildGeofenceData {
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"regions" ofType:#"plist"];
_regionArray = [NSArray arrayWithContentsOfFile:plistPath];
NSMutableArray *geofences = [NSMutableArray array];
for(NSDictionary *regionDict in _regionArray) {
CLRegion *region = [self mapDictionaryToRegion:regionDict];
[geofences addObject:region];
}
return [NSArray arrayWithArray:geofences];
}
- (CLRegion*)mapDictionaryToRegion:(NSDictionary*)dictionary {
NSString *title = [dictionary valueForKey:#"title"];
CLLocationDegrees latitude = [[dictionary valueForKey:#"latitude"] doubleValue];
CLLocationDegrees longitude =[[dictionary valueForKey:#"longitude"] doubleValue];
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
//CLLocationDistance regionRadius = 50.000;
CLLocationDistance regionRadius = [[dictionary valueForKey:#"radius"] doubleValue]; //<--STOD DOUBLE ISTÄLLET
return [[CLRegion alloc] initCircularRegionWithCenter:centerCoordinate
radius:regionRadius
identifier:title];
}
- (void)initializeLocationUpdates {
[_locationManager startUpdatingLocation];
}
#pragma mark - Location Manager - Region Task Methods
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#"Entered Region - %#", region.identifier);
[self showRegionAlert:#"Entering Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"Exited Region - %#", region.identifier);
[self showRegionAlert:#"Exiting Region" forRegion:region.identifier];
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Started monitoring %# region", region.identifier);
}
#pragma mark - Location Manager - Standard Task Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.coordinateLabel.text = [NSString stringWithFormat:#"%f,%f",newLocation.coordinate.latitude, newLocation.coordinate.longitude];
}
#pragma mark - Alert Methods
- (void) showRegionAlert:(NSString *)alertText forRegion:(NSString *)regionIdentifier {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:alertText
message:regionIdentifier
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
- (void)showAlertWithMessage:(NSString*)alertText {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Location Services Error"
message:alertText
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
#end
Appdelegate.h
#import <UIKit/UIKit.h>
#class ViewController;
#interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ViewController *viewController;
#end
Appdelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
//DERAS ALLTSÅ KML!!
#synthesize window;
#synthesize viewController;
//
//Deras alltså KML!!
#pragma mark -
#pragma mark Application lifecycle
//
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
//Deras alltså KML!!
[window addSubview:viewController.view];
//
return YES;
}
//Deras alltså KML!!!
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
//
#end

How to check if geolocation is enabled on iPhone?

How to check if localization is enable on iPhone?
I need to check if geolocation is enable in viewDidLoad method.
This is my viewDidLoad method:
- (void)viewDidLoad {
[super viewDidLoad];
// 1. Check connection
[self performSelector:#selector(checkConnection)];
// 2. Loader (activity indicator) ...
progressViewController = [[ProgressViewController alloc] initWithNibName:#"ProgressViewController" bundle:nil];
[self.view addSubview:progressViewController.view];
// 3. Active geolocation
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[self startGps];
// 4. Data tableView
NSMutableArray *arrEvents = [[NSMutableArray alloc] init];
[[ListaEventiSingleton sharedListaEventi] setArrEvents:arrEvents];
[arrEvents release];
// 5. remove loader (activity indicator)
[progressViewController.view removeFromSuperview];
}
//delegate localization
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (newLocation.horizontalAccuracy < 0) {
locality = #"Non riesco a localizzarti..\n Refresha!";
}
else {
CLLocationCoordinate2D here = newLocation.coordinate;
latitudine = [NSString stringWithFormat:#"%f", here.latitude];
longitudine = [NSString stringWithFormat:#"%f", here.longitude];
[self getAddressFromGmaps];
[self stopGps];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(stopUpdatingLocalizzazione) object:nil];
}
labelLocality.text = locality;
// 4. Load data for the table view
[self performSelectorOnMainThread:#selector(loadEvents) withObject:nil waitUntilDone:YES];
[tableViewEvents reloadData];
// 5. remove activity indicator
[progressViewController.view removeFromSuperview];
}
I think you want [CLLocationManager locationServicesEnabled].