【问题标题】:Implementing iPhone Location in Objective-C在 Objective-C 中实现 iPhone 定位
【发布时间】:2013-05-12 19:46:22
【问题描述】:

所以我一直在尝试学习如何在 Objective-C 中实现 iPhone 定位。目前我有几个文件:

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

我确定我有时犯了一个重大错误,但我很困惑,并不真正理解它是什么。尝试运行此程序时出现 2 个重大错误。

【问题讨论】:

  • 我不明白您为什么要实现定位器类(无论如何您都不使用它)。并且您必须声明您的 viewController 符合 CLLocationManagerDelegate,即:@interface ViewController : UIViewController

标签: iphone ios objective-c location


【解决方案1】:
@interface ViewController : UIViewController
@end

必须变成:

@interface ViewController : UIViewController <CLLocationManagerDelegate>
@end

它现在应该可以工作了。

编辑: 如果您只想获取 iDevice 坐标,请不要使用自己的 locatorclass,直接在 viewController 中使用它会更快。

因为如果你想用自己的班级来做这件事,你必须:

  • 创建一个 CLLocationManager 变量
  • 设置特定的初始化
  • 声明一些方法来启动对 iDevice 位置的跟踪
  • 声明一个额外的方法来返回您的坐标或将您的 CLLocationManager 变量定义为公共!

而且更容易解释:)

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    通常我会将 CLLocationManager 设为类变量,如下所示:

    @interface ViewController : UIViewController <CLLocationManagerDelegate>
    
    @property (strong, nonatomic) CLLocationManager *locationManager
    
    @end
    

    然后你就可以调用了:

    [self.locationManager stopUpdatingLocation];
    

    当你想要的时候。你还需要实现:

    -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    }
    

    在您的视图控制器中接收具有位置数据的委托回调。

    【讨论】:

      猜你喜欢
      • 2011-04-14
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2018-03-28
      相关资源
      最近更新 更多