iOS 8 Map Kit Obj-C Cannot Get Users Location - objective-c

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;
}

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!!");
}
}
}

How to find the current location address?

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];

unable to Get GPS Location "BSXPCMessage received error for message: Connection interrupted"

I am trying to get the Location "Latitude & Longitude".
The steps which I did as follow:
In CurrentLocationViewController.m:
#implementation CurrentLocationViewController {
CLLocationManager *locationManager;
}
Then in CurrentLocationViewController.h
#import <CoreLocation/CoreLocation.h>
#interface CurrentLocationViewController : UIViewController <CLLocationManagerDelegate>
Back to In CurrentLocationViewController.m:
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
locationManager = [[CLLocationManager alloc] init];
}
return self;
}
- (IBAction)getLocation:(id)sender {
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError %#", error);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation !=nil) {
self.longitudeLabel.text = [NSString stringWithFormat:#"%0.8f", currentLocation.coordinate.longitude];
self.latitudeLabel.text = [NSString stringWithFormat:#"%0.8f", currentLocation.coordinate.latitude];
}
}
I put Break point on each methods, and even though, when I run the application, i got message in the Console: BSXPCMessage received error for message: Connection interrupted.
Any idea?
I got the same error message, still can't fix 'BSXPCMessage' error, but about the location part, I guess you're running iOS 7 version codes on iOS 8?
If so, try this:
Add [locationManager requestAlwaysAuthorization] or [locationManager requestWhenInUseAuthorization] above [locationManager startUpdatingLocation]
open Info.plist, add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription into 'information property list' with a message
That's it, hope this can help you.
Getting the same error message when working with AVFoundation. Images and videos. It's not specific to what you do.

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

Tab bar Controller and Facebook Connect Issues Xcode 4.3 IOS 5.1

I am trying to connect to the facebook and take the users name and picture, so far i can connect and fetch user name . i have a working code can be downloaded from here (single view application)
But if i put a tab bar controller to the code, it can not receive a response from facebook.
I add a tabbar controller programatically like below code
in app.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Regular Code
/*self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
*/
//Tab bar controller code
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController *viewController1 = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.rootController = [[[UITabBarController alloc] init] autorelease];
self.rootController.viewControllers = [NSArray arrayWithObjects:viewController1, nil];
self.window.rootViewController = self.rootController;
[self.window makeKeyAndVisible];
return YES;
}
// This method will be used for iOS versions greater than 4.2.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[_viewController facebook] handleOpenURL:url];
}
If i put a breaking point at line handleOpenurl In NSUrl there is this= fbAPPID://authorize/#access_token=BABABSbbsabsbabb
I guess access_token means i have succesfully loged in . So tab bar doesnt block me to login put blokcs my facebook methods in Viewcontroller.m
Without tab bar all methods in Viewcontroller.m works great when i add tab bar and breakpoints none of the facebook methods below works. I dont get any errors though.
-(void)request:(FBRequest *)request didLoad:(id)result
-(void)fbDidLogin
ViewController.m
#import "ViewController.h"
#import "FBConnect.h"
#import "Facebook.h"
#implementation ViewController
#synthesize btnLogin;
#synthesize btnPublish;
#synthesize lblUser;
#synthesize actView;
#synthesize facebook;
#synthesize permissions;
#synthesize isConnected;
#synthesize imageView;
// The alert view that will be shown while the game will upload to facebook.
UIAlertView *msgAlert;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
-(void)checkForPreviouslySavedAccessTokenInfo{
// Initially set the isConnected value to NO.
isConnected = NO;
// Check if there is a previous access token key in the user defaults file.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] &&
[defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
// Check if the facebook session is valid.
// If it’s not valid clear any authorization and mark the status as not connected.
if (![facebook isSessionValid]) {
[facebook authorize:nil];
isConnected = NO;
}
else {
isConnected = YES;
}
}
}
-(void)setLoginButtonImage{
UIImage *imgNormal;
UIImage *imgHighlighted;
UIImageView *tempImage;
// Check if the user is connected or not.
if (!isConnected) {
// In case the user is not connected (logged in) show the appropriate
// images for both normal and highlighted states.
imgNormal = [UIImage imageNamed:#"LoginNormal.png"];
imgHighlighted = [UIImage imageNamed:#"LoginPressed.png"];
}
else {
imgNormal = [UIImage imageNamed:#"LogoutNormal.png"];
imgHighlighted = [UIImage imageNamed:#"LogoutPressed.png"];
}
// Get the screen width to use it to center the login/logout button.
// We’ll use a temporary image view to get the appopriate width and height.
float screenWidth = [UIScreen mainScreen].bounds.size.width;
tempImage = [[UIImageView alloc] initWithImage:imgNormal];
[btnLogin setFrame:CGRectMake(screenWidth / 2 - tempImage.frame.size.width / 2, btnLogin.frame.origin.y, tempImage.frame.size.width, tempImage.frame.size.height)];
// Set the button’s images.
[btnLogin setBackgroundImage:imgNormal forState:UIControlStateNormal];
[btnLogin setBackgroundImage:imgHighlighted forState:UIControlStateHighlighted];
// Release the temporary image view.
[tempImage release];
}
-(void)showActivityView{
// Show an alert with a message without the buttons.
msgAlert = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Please wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[msgAlert show];
// Show the activity view indicator.
actView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];
[actView setCenter:CGPointMake(160.0, 350.0)];
[actView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:actView];
[actView startAnimating];
}
-(void)stopShowingActivity{
[actView stopAnimating];
[msgAlert dismissWithClickedButtonIndex:0 animated:YES];
}
-(void)saveAccessTokenKeyInfo{
// Save the access token key info into the user defaults.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Set the permissions.
// Without specifying permissions the access to Facebook is imposibble.
permissions = [[NSArray arrayWithObjects:#"read_stream", #"publish_stream", nil] retain];
// Set the Facebook object we declared. We’ll use the declared object from the application
// delegate.
facebook = [[Facebook alloc] initWithAppId:#"331327710279153" andDelegate:self];
// Check if there is a stored access token.
[self checkForPreviouslySavedAccessTokenInfo];
// Depending on the access token existence set the appropriate image to the login button.
[self setLoginButtonImage];
// Specify the lblUser label's message depending on the isConnected value.
// If the access token not found and the user is not connected then prompt him/her to login.
if (!isConnected) {
[lblUser setText:#"Tap on the Login to connect to Facebook"];
}
else {
// Get the user's name from the Facebook account.
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
// Initially hide the publish button.
[btnPublish setHidden:YES];
}
- (void)viewDidUnload
{
[self setBtnLogin:nil];
[self setLblUser:nil];
[self setBtnPublish:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
// Keep this just for testing purposes.
NSLog(#"received response");
}
-(void)request:(FBRequest *)request didLoad:(id)result{
// With this method we’ll get any Facebook response in the form of an array.
// In this example the method will be used twice. Once to get the user’s name to
// when showing the welcome message and next to get the ID of the published post.
// Inside the result array there the data is stored as a NSDictionary.
if ([result isKindOfClass:[NSArray class]]) {
// The first object in the result is the data dictionary.
result = [result objectAtIndex:0];
}
// Check it the “first_name” is contained into the returned data.
if ([result objectForKey:#"first_name"]) {
// If the current result contains the "first_name" key then it's the user's data that have been returned.
// Change the lblUser label's text.
[lblUser setText:[NSString stringWithFormat:#"Welcome %#!", [result objectForKey:#"first_name"]]];
// Show the publish button.
[btnPublish setHidden:NO];
}
else if ([result objectForKey:#"id"]) {
// Stop showing the activity view.
[self stopShowingActivity];
// If the result contains the "id" key then the data have been posted and the id of the published post have been returned.
UIAlertView *al = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Your message has been posted on your wall!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[al show];
[al release];
}
}
-(void)request:(FBRequest *)request didFailWithError:(NSError *)error{
NSLog(#"%#", [error localizedDescription]);
// Stop the activity just in case there is a failure and the activity view is animating.
if ([actView isAnimating]) {
[self stopShowingActivity];
}
}
-(void)fbDidLogin{
// Save the access token key info.
[self saveAccessTokenKeyInfo];
// Get the user's info.
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
-(void)fbDidNotLogin:(BOOL)cancelled{
// Keep this for testing purposes.
//NSLog(#"Did not login");
UIAlertView *al = [[UIAlertView alloc] initWithTitle:#"My test app" message:#"Login cancelled." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[al show];
}
-(void)fbDidLogout{
// Keep this for testing purposes.
//NSLog(#"Logged out");
// Hide the publish button.
[btnPublish setHidden:YES];
}
- (IBAction)LoginOrLogout {
// If the user is not connected (logged in) then connect.
// Otherwise logout.
if (!isConnected) {
[facebook authorize:permissions];
// Change the lblUser label's message.
[lblUser setText:#"Please wait..."];
}
else {
[facebook logout:self];
[lblUser setText:#"Tap on the Login to connect to Facebook"];
}
isConnected = !isConnected;
[self setLoginButtonImage];
}
- (IBAction)Publish {
// Show the activity indicator.
[self showActivityView];
// Create the parameters dictionary that will keep the data that will be posted.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My test app", #"name",
#"http://www.google.com", #"link",
#"FBTestApp app for iPhone!", #"caption",
#"This is a description of my app", #"description",
#"Hello!\n\nThis is a test message\nfrom my test iPhone app!", #"message",
nil];
// Publish.
// This is the most important method that you call. It does the actual job, the message posting.
[facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc {
[btnLogin release];
[lblUser release];
[btnPublish release];
[actView release];
[facebook release];
[permissions release];
[super dealloc];
}
#end
I am confused how can i make this tab bar controlling working.
I have changed the design
Now Login view is displayed first then it continues to real app which has tab bar controller.
Issue was _viewcontroller facebook , when _viewcontroller has been called it was not returning any thing
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[_viewController facebook] handleOpenURL:url];
}
So I changed my code(especially _viewcontroller line) to below code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController * viewController1 = [[[VoteMe alloc] initWithNibName:#"VoteMe" bundle:nil] autorelease];
UIViewController *viewController2 = [[[PostController alloc] initWithNibName:#"PostController" bundle:nil] autorelease];
UIViewController *viewController3 = [[[FriendsController alloc] initWithNibName:#"FriendsController" bundle:nil] autorelease];
UIViewController *viewController4 = [[[Responses alloc] initWithNibName:#"Responses" bundle:nil] autorelease];
UIViewController *viewController5 = [[[User alloc] initWithNibName:#"User" bundle:nil] autorelease];
self.rootController = [[[UITabBarController alloc] init] autorelease];
self.rootController.viewControllers = [NSArray arrayWithObjects:viewController1,viewController2,viewController3,viewController4,viewController5, nil];
self.window.rootViewController = self.rootController;
[self.window makeKeyAndVisible];
loginView=[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
[self.window addSubview:loginView.view];
return YES;
}
// This method will be used for iOS versions greater than 4.2.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[loginView facebook] handleOpenURL:url];
}
It works fine