» 首頁 » 討論區 » iOS程式討論 »CoreLocation - GPS範例

CoreLocation - GPS範例

發表人: Seachaos
積分: 2432
發表時間: 2012-02-02 22:32:57
要在iOS中使用CoreLocation之前,要先在Project內加入CoreLocation這個framework

然後要實做 CLLocationManagerDelegate
[sea:javaCode]
#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(@"Core location get position success.");
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"Core location error!");
}
[/sea]

另外可以用getter的方式來alloc CLLocationManager
[sea:javaCode]
- (CLLocationManager*)locationManager{
if(locationManager_!=nil)
return locationManager_;
NSLog(@"CLLocation Manager alloc");
locationManager_ = [[CLLocationManager alloc] init];
locationManager_.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager_.delegate = self;
return locationManager_;
}
[/sea]

要取得GPS座標方法:
[sea:javaCode]
CLLocation *location = self.locationManager.location;
[NSNumber numberWithDouble:location.coordinate.latitude];
[NSNumber numberWithDouble:location.coordinate.longitude];
[/sea]

另外開始和停止是
[sea:javaCode]
[self.locationManager startUpdatingLocation];
[self.locationManager stopUpdatingLocation];
[/sea]
在 iPhone/ iPod / iPad 因為他們的電量有限,記得不用時要將GPS關閉
發表人: Seachaos
積分: 2432
發表時間: 2012-02-02 22:37:54
另外在 XCode 4.1中,可能iOS的Simulator會有Bug
出現訊息:
server did not accept client registration 68

可以用以下Code Hack掉
[sea:javaCode]
@implementation CLLocationManager (TemporaryHack)
- (void)hackLocationFix
{
CLLocation *location = [[CLLocation alloc] initWithLatitude:42 longitude:-50];
[[self delegate] locationManager:self didUpdateToLocation:location fromLocation:nil];
}

- (void)startUpdatingLocation
{
[self performSelector:@selector(hackLocationFix) withObject:nil afterDelay:0.1];
}
@end
[/sea]

來源:http://forums.bignerdranch.com/viewtopic.php?f=79&t=2069