[英]How to load post with CLLocation
我正在構建一個iPhone應用程序,該應用程序使用AFNetworking將數據獲取和發布到Rails支持的服務器。 一切正常,但現在我嘗試傳遞lat / lng參數,以便加載附近的帖子。 我很確定我設置正確-heroku日志顯示了使用lat / lng發出的get請求-但我遇到的問題是一個更基本的問題。 在我的indexViewController中,我嘗試在viewDidLoad方法中調用
[self loadPosts]
但是我遇到了麻煩,因為在此之下,當我定義loadPosts並調用fetchNearbyPosts方法時,我需要調用CLLocation作為其實現的一部分-這會導致未聲明的標識符錯誤。 我可以通過聲明以下內容解決此問題:
loadPosts:(CLLocation *)location {
但是,然后在viewDidLoad中,當我更改[self loadPosts:(CLLocation *)location]; 該行現在獲得“位置”的未聲明的標識符錯誤。 所以我要轉圈。
我的fetchNearbyPosts方法是這樣的:
+ (void)fetchNearbyPosts:(CLLocation *)location
withBlock:(void (^)(NSArray *posts, NSError *error))completionBlock
{
NSDictionary *parameters = @{
@"lat": @(location.coordinate.latitude),
@"lng": @(location.coordinate.longitude)
};
[[APIClient sharedClient] getPath:@"/posts" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (operation.response.statusCode ==200) {
NSArray *posts = [Post postsWithJSON:responseObject];
completionBlock(posts, nil);
} else {
NSLog(@"Recieved an HTTP %d: %@", operation.response.statusCode, responseObject);
completionBlock(nil, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completionBlock(nil, error);
NSLog(@"Error: %@", error);
}];
}
我完整的loadPosts方法是:
- (void)loadPosts:(CLLocation *)location {
[Post fetchNearbyPosts:location withBlock:^(NSArray *posts, NSError *error) {
if (posts) {
NSLog(@"Recieved %d posts", posts.count);
self.posts = [NSMutableArray arrayWithArray:posts];
[self.tableView reloadData];
[self.tableView setNeedsLayout];
} else {
[[[UIAlertView alloc] initWithTitle:@"ERROR"
message:@"Couldn't fetch the posts."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}];
}
我認為這很基本-但是如何使用CLLocation在ViewDidLoad中調用loadPosts呢? 任何幫助將不勝感激。 謝謝
據我了解,您需要獲取當前位置以將其作為-(void)loadPosts:(CLLocation *)location方法的參數傳遞,該方法將在viewDidLoad中調用
將此方法添加到您的視圖控制器:
-(CLLocation) getLocation{
CLLocationManager * locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation * location = [locationManager location];
return location;
}
然后,在您的viewDidLoad中調用此
[self loadPosts: [self getLocation]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.