簡體   English   中英

在Objective-C中實現iPhone位置

[英]Implementing iPhone Location in Objective-C

因此,我一直試圖學習如何在Objective-C中實現iPhone的位置。 目前,我有幾個文件:

定位器

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

@interface locator : NSObject
- (void)locationManager:(CLLocationManager *)manager;
@end

定位器

#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個主要錯誤。

@interface ViewController : UIViewController
@end

必須成為:

@interface ViewController : UIViewController <CLLocationManagerDelegate>
@end

現在應該可以工作了。

編輯 :如果只想獲取iDevice坐標,請不要使用自己的locator類,直接在viewController中使用它會更快。

因為如果您想在自己的班上這樣做,則必須:

  • 創建一個CLLocationManager變量
  • 設置一個特定的初始化
  • 聲明一些方法以啟動對iDevice位置的跟蹤
  • 聲明一個額外的方法來返回您的坐標或將您的CLLocationManager變量定義為public!

而且更容易解釋:)

希望這可以幫助。

通常,我會將CLLocationManager設為類變量,如下所示:

@interface ViewController : UIViewController <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager

@end

然后,您將可以致電:

[self.locationManager stopUpdatingLocation];

當你想要的時候。 您還需要實現:

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

}

在您的ViewController中,接收具有位置數據的委托回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM