问题
So ive been trying to learn how to implement iPhone location in Objective-C. Currently I have several files:
locator.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface locator : NSObject
- (void)locationManager:(CLLocationManager *)manager;
@end
locator.m
#import "locator.h"
#import <CoreLocation/CoreLocation.h>
@implementation locator
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationDegrees latitude = newLocation.coordinate.latitude;
CLLocationDegrees longitude = newLocation.coordinate.longitude;
}
@end
viewController.h
#import <UIKit/UIKit.h>
#import "locator.h"
@interface ViewController : UIViewController
@end
viewController.m
#import "ViewController.h"
#import "locator.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self; // Set your controller as a <CLLocationManagerDelegate>.
[locationManager startUpdatingLocation];
[super viewDidLoad];
}
@end
Im sure ive made a major error sometimes but im quite confused and dont really understand what it is. Im getting 2 major errors when trying to run this.
回答1:
@interface ViewController : UIViewController
@end
Must become :
@interface ViewController : UIViewController <CLLocationManagerDelegate>
@end
It should work now.
EDIT :
Do not use your own locator
class if you just want to get the iDevice coordinates, it's faster to use this directly in your viewController.
Because if you want to do this with your own class you have to :
- create a CLLocationManager variable
- set up a specific init
- declare some method to launch de tracking of the position of the iDevice
- declare an extra method to return your coordinates or define your CLLocationManager variable as public !
And it's easier to explain :)
Hope this helps.
回答2:
Usually I would make the CLLocationManager a class variable like so:
@interface ViewController : UIViewController <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager
@end
Then you will be able to call:
[self.locationManager stopUpdatingLocation];
when you desire. Also you need to implement:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
}
In your viewcontroller to receive the delegate callback that has the location data.
来源:https://stackoverflow.com/questions/16511350/implementing-iphone-location-in-objective-c