gpt4 book ai didi

iOS CLLocationManagerDelegate didUpdateToLocation 未被调用

转载 作者:行者123 更新时间:2023-11-29 02:47:19 25 4
gpt4 key购买 nike

我正在创建一个使用核心位置的应用程序,这是我的代码:

.h :

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController
<CLLocationManagerDelegate>
@property(strong,nonatomic) CLLocationManager *manager;
@end

.m :

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@end
@implementation ViewController
@synthesize manager;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.manager)
{
self.manager=[CLLocationManager new];
}
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[self.manager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation * currentLocation = (CLLocation *)[locations lastObject];
NSLog(@"Location: %@", currentLocation);
if (currentLocation != nil)
{
NSLog([NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
NSLog([NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
}
}
@end

问题是 didUpdateToLocation 没有被调用。我尝试在其中放置一个断点,但什么也没发生。

最佳答案

要使 iOS 位置跟踪正常工作,先决条件如下,顺序也很重要:

  1. 将您的类定义为 CLLocationManagerDelegate
  2. 实例化 CLLocationManager 实例。
  3. 将其delegate 设置为self
  4. 设置它的各种属性(准确度等)
  5. 在需要时调用 [CLLocationManagerDelegate startUpdatingLocation]
  6. 在您的委托(delegate)方法 didUpdateLocations 中监听位置更新,该方法在指定为 CLLocationManagerDelegate 的类中实现。

对于您的代码,以下是您需要更正的地方:

-(IBAction)submit
{
[self.manager startUpdatingLocation];
}

- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.manager)
{
self.manager=[CLLocationManager new];
}
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}

简而言之,在告诉它开始更新位置之前,您需要实例化它并正确设置它的属性。目前你正在以相反的方式进行。

更新

此外,您的委托(delegate)方法 didUpdateToLocation 自 iOS 6 起已弃用。您必须将其替换为 newer method ,像这样:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation * currentLocation = (CLLocation *)[locations lastObject];
NSLog(@"Location: %@", currentLocation);
if (currentLocation != nil)
{
self.latitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
self.longitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
}
}

关于iOS CLLocationManagerDelegate didUpdateToLocation 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com