2014-02-08 16 views
0

我想做一个HTTP请求,并且请求的一部分包含lat和lng。在模型中使用委托来传递它们之间的信息

为了得到这些我有一个位置模式。其中一位代表让我知道何时准备好位置。当发生这种情况时,我会调用我的Foursquare模型中实现的自定义委托。

我通过创建位置模型的实例并调用startUpdatingLocation方法来启动我的MainViewController中的所有内容。实施看起来是这样的:

选址模型:

- (void)startLocationManager 
{ 
    _locationManager = [[CLLocationManager alloc] init]; 
    _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; 
    _locationManager.delegate = self; 

    [_locationManager startUpdatingLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{ 
    NSLog(@"Error:%@", error.userInfo); 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
{ 
    if (locations) { 
     _location = [locations lastObject]; 
     [self.delegate location:self didFinishFindingLocation:_location]; 
    } 

} 

Foursquare模式:

- (void)location:(Location *)loc didFinishFindingLocation:(CLLocation *)location 
{ 
    NSString *search = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?ll=%f,%f&radius=2000&categoryId=4d4b7105d754a06374d81259&client_id=%@&client_secret=%@&v=%@", location.coordinate.latitude, location.coordinate.longitude, kFourdquareAPIKey, fFoursquareSecret, [Foursquare getCurrentDate]]; 

    NSURL *url = [NSURL URLWithString:search]; 
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     NSDictionary *dataDictionary = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
     self.dataResponse = dataDictionary[@"response"][@"venues"]; 
     NSLog(@"%@", self.dataResponse); 
    }]; 

    [task resume]; 
} 

最后,我做这在我的MainViewController:

Location *location = [[Location alloc] init]; 
[location startLocationManager]; 

没有被记录到控制台,模拟器不会要求我获取位置的权限。没有。

1)使用这样的代表是错误的吗? 2)有没有更好的方法?

鉴于1的答案是否定的,我的代码有什么问题?

+0

你是否正在调用 - (void)location:(Location *)loc didFinishFindingLocation:(CLLocation *)location。我怀疑你是否为你的Foursquare模型设置代表。 – Pawan

回答

0

您是否为您的location:didFinishFindingLocation:方法设置了代表?从上面的代码看起来并不像它。
无论如何,虽然它可能工作,但这不是正确的方法。如果你需要你的模型进行沟通,最好的办法是同时进行解耦,这将是本地通知。
您可能想要阅读this article以了解它们的工作原理。

+0

我认为使用委托在这种情况下是好的,只要你只需要1:1通信...如果你需要1:很多,那就是当NSNotificationCenter更合理 –

+0

我不完全确定我明白你的意思。在我的foursquare模型中,我放置了?因为我已经有了那个 –

+0

或者你的意思是loc.delegate = self,在实现委托方法的Foursquare.m中?在任何情况下,它不起作用 –

-1

你是否在四个平方米初始化了这个?
Location * location = [[Location alloc] init]; location.delegate = self;

+0

不,在我的MainViewController.m中。四方。是一个模型,没有vewDidLoad –

+0

没有看到那部分。 – iDev

相关问题