gpt4 book ai didi

iphone - 委托(delegate)上设置的事件

转载 作者:行者123 更新时间:2023-11-28 19:13:06 24 4
gpt4 key购买 nike

我想在这里理解一些关于委托(delegate)和回调的概念。基本上,我正在尝试发出一个基于邮政编码的 http 请求。因此,在发出 http 请求之前,我会调用位置管理器并获取邮政编码,但是,在这样的持续时间内,我必须等待异步完成该任务并获得反馈。这里的问题是,我从 location-manager 设置的委托(delegate)与 http-request 类没有链接。因此,我试图了解如何将信息从委托(delegate)传递回 http 请求。我正在研究 block ,但无论如何 block 中是否还有可以等待代表响应的 block ?或者也可以在异步任务中设置为 BOOL 属性,完成后可以触发请求。除了 GCD 之外,我没有尝试过多的 block ,所以我仍在努力解决这个问题。

我欢迎任何建议。

最佳答案

这是一个草图 -(忽略错误条件和位置数据缓存问题)。这都可以放在 viewController 中。有一个 block 用于获取邮政编码,但如果您愿意,其余部分可以通过委托(delegate)完成。

//initialise locationManager once (eg in viewDidLoad)
- (void) initialiseLocationManager
{
CLLocationManager* locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
[locationManager setDistanceFilter:500];
self.locationManager = locationManager;
}

//[self startLocating] whenever you want to initiate another http-request
- (void) startLocating
{
[self.locationManager startUpdatingLocation];
}

//locationManager delegate method
//this will get triggered after [self startLocating]
//when a location result is returned
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation* location = [locations lastObject];
CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location
completionHandler:^(NSArray *placemarks, NSError *error){
CLPlacemark* placemark = [placemarks objectAtIndex:0];
NSString* zip = [placemark postalCode];

/*
implement your http-request code here using the zip string
there are various ways to do this
but two ways your result will arrive...

1 - as a delegate callback
so you would implement the relevant delegate method
(in this same viewController) to use the result

2 - as a completion block
so your result-using method would be that block
*/

}];
[self.locationManager stopUpdatingLocation];
}

关于iphone - 委托(delegate)上设置的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13938322/

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