gpt4 book ai didi

ios - 从位置类向 ViewController 发送坐标信息

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

我正在尝试编写一个可以更新设备位置的应用。

我设置了一个 GPS_Obtainer 类,它将获取设备的位置。 GPS_Obtainer 类会将位置信息转发给 View Controller 。

我尝试使用协议(protocol),但失败了。

最好的方法是什么?如何?

最佳答案

您可以选择使用所有三种方式,NotificationObserversProtocol 来发送位置更新,我正在演示协议(protocol)方式,见下文

首先,您可以为您的 GPS_Obtainer 类创建一个 Singleton,如下所示。

GPS_Obtainer.h

#import "GPS_Obtainer.h"

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

@protocol GPS_ObtainerDelegate <NSObject>

-(void)locationDidUpdated:(CLLocation *)location;

@end

@interface GPS_Obtainer : NSObject

@property (nonatomic, strong) id<GPS_ObtainerDelegate> delegate;

+ (GPS_Obainer*)sharedSingleton;

@end

GPS_Obtainer.m

@interface GPS_Obtainer()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation GPS_Obtainer

- (id)init {
self = [super init];

if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager startUpdatingLocation];
}

return self;
}

+ (GPS_Obtainer*)sharedSingleton {

static GPS_Obtainer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [GPS_Obtainer new];
});
return sharedSingleton;
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{

}

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

if(self.delegate && [self.delegate respondsToSelector:@selector(locationDidUpdated:)]){
[self.delegate locationDidUpdated:newLocation];
}

}

@end

然后你只需要在 ViewController 中设置类的委托(delegate),它将像下面这样接收它

ViewController.m

-(void)viewDidLoad{
[[GPS_Obtainer sharedSingleton] setDelegate:self];
}

-(void)locationDidUpdated:(CLLocation *)location{
//HERE you get the location updates
}

-(void)dealloc{
[[GPS_Obtainer sharedSingleton] setDelegate:nil];
}

希望以上有所帮助。

干杯。

关于ios - 从位置类向 ViewController 发送坐标信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38005276/

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