Implementing iPhone Location in Objective-C

半世苍凉 提交于 2021-01-29 08:12:15

问题


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 locatorclass 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!