2011-06-29 24 views
34

我要找到我的當前位置與CoreLocation找到你的當前位置,我試過多種方法,但到目前爲止我CLLocationManager纔回到0的..(0.000.00.000)。如何使用CoreLocation

這裏是我的代碼(更新工作):

進口

#import <CoreLocation/CoreLocation.h> 

申報

IBOutlet CLLocationManager *locationManager; 
IBOutlet UILabel *latLabel; 
IBOutlet UILabel *longLabel; 

功能

- (void)getLocation { //Called when needed 
    latLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.latitude]; 
    longLabel.text = [NSString stringWithFormat:@"%f", locationManager.location.coordinate.longitude]; 
} 

- (void)viewDidLoad { 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 
} 

回答

77

可以使用CoreLocation這樣找到您的位置:

進口CoreLocation

#import <CoreLocation/CoreLocation.h> 

聲明CLLocationManager

CLLocationManager *locationManager; 

初始化locationManagerviewDidLoad並創建可return當前位置爲NSString功能:

- (NSString *)deviceLocation { 
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude]; 
} 

- (void)viewDidLoad 
{ 
    locationManager = [[CLLocationManager alloc] init]; 
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move 
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m 
    [locationManager startUpdatingLocation]; 
} 

並調用deviceLocation函數將返回預期的位置:

NSLog(@"%@", [self deviceLocation]); 

這僅僅是一個例子。在沒有用戶準備好的情況下初始化CLLocationManager不是一個好主意。當然,在CLLocationManager已經初始化後,locationManager.location.coordinate可以用來隨意得到latitudelongitude

不要忘記在項目設置中的「構建階段」選項卡(Targets->Build Phases->Link Binary)下添加CoreLocation.framework

+0

但這些方法不再返回當前的位置。即時通訊使用Xcode 6,但它使用Xcode 5時工作得很好。 – SARATH

15

使用CLLocationManager,您不必立即獲取位置信息。 GPS和其他獲取位置信息的設備可能未被初始化。他們可能需要一段時間才能獲得任何信息。相反,您需要創建一個委託對象來響應locationManager:didUpdateToLocation:fromLocation:,然後將其設置爲位置管理器的委託。

看到here

+2

本文HTTP當前的位置:// mobileorchard。COM/HELLO-有-A-corelocation教程/(從相關計算器問題拍攝)表明該怎麼做。 – ThomasW

-2

在這裏,您可以顯示與註釋詳情

在ViewController.h

#import <UIKit/UIKit.h> 
#import <CoreLocation/CoreLocation.h> 


//My 
#import <MapKit/MapKit.h> 
#import <MessageUI/MFMailComposeViewController.h> 

@interface ViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,MFMailComposeViewControllerDelegate> 
{ 
    IBOutlet UILabel *lblLatitiude; 
    IBOutlet UILabel *lblLongitude; 
    IBOutlet UILabel *lblAdress; 
} 
//My 
@property (nonatomic, strong) IBOutlet MKMapView *mapView; 


-(IBAction)getMyLocation:(id)sender; 

@end 

在ViewController.m

#import "ViewController.h" 


@interface ViewController() 

@end 

@implementation ViewController{ 
    CLLocationManager *locationManager; 
    CLGeocoder *geocoder; 
    CLPlacemark *placemark; 
} 

@synthesize mapView; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    locationManager = [[CLLocationManager alloc] init]; 
    geocoder = [[CLGeocoder alloc] init]; 

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
    NSMutableDictionary *defaultsDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"[email protected]", @"fromEmail", 
               @"[email protected]", @"toEmail", 
               @"smtp.gmail.com", @"relayHost", 
               @"[email protected]", @"login", 
               @"[email protected]", @"pass", 
               [NSNumber numberWithBool:YES], @"requiresAuth", 
               [NSNumber numberWithBool:YES], @"wantsSecure", nil]; 

    [userDefaults registerDefaults:defaultsDictionary]; 


    self.mapView.delegate=self; 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Custom Methods 


-(IBAction)getMyLocation:(id)sender{ 
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 

    [locationManager startUpdatingLocation]; 
} 


#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) { 
     lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
     lblLatitiude.text = [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]; 

      lblAdress.text = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@", 
           placemark.subThoroughfare, placemark.thoroughfare, 
           placemark.postalCode, placemark.locality, 
           placemark.administrativeArea, 
           placemark.country]; 



      MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, 800, 800); 
      [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES]; 

      // Add an annotation 
      MKPointAnnotation *point = [[MKPointAnnotation alloc] init]; 
      point.coordinate = currentLocation.coordinate; 
      point.title = @"Where am I?"; 
      point.subtitle = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@", 
           placemark.subThoroughfare, placemark.thoroughfare, 
           placemark.postalCode, placemark.locality, 
           placemark.administrativeArea, 
           placemark.country]; 


      [self.mapView addAnnotation:point]; 


     } else { 
      NSLog(@"%@", error.debugDescription); 
     } 
    } ]; 


} 

//My 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation 
{ 
    MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"]; 
    annotationView.canShowCallout = YES; 
    annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 

    return annotationView; 
} 

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control 
{ 

    [self getSignScreenShot]; 

    MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init]; 
    controller.mailComposeDelegate = self; 
    [controller setSubject:@"My Subject"]; 
    [controller setMessageBody:@"Hello there." isHTML:NO]; 
    if (controller) [self presentModalViewController:controller animated:YES]; 
} 

- (void)mailComposeController:(MFMailComposeViewController*)controller 
      didFinishWithResult:(MFMailComposeResult)result 
         error:(NSError*)error; 
{ 
    if (result == MFMailComposeResultSent) { 
     NSLog(@"It's away!"); 
    } 
    [self dismissModalViewControllerAnimated:YES]; 
} 

//----------------------------------------------------------------------------------- 
//This methos is to take screenshot of map 
//----------------------------------------------------------------------------------- 
-(UIImage *)getSignScreenShot 
{ 
    CGRect rect = CGRectMake(self.mapView.frame.origin.x,self.mapView.frame.origin.y-50,self.mapView.frame.size.width+60,self.mapView.frame.size.height+15); 
    UIGraphicsBeginImageContextWithOptions(self.mapView.frame.size, NO, 1.0); 
    [self.mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); 
    CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], rect); 
    UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 

    return newImage; 
}