Mobile/iOS

[iOS]8이상에서 위치정보 사용하기

out of coding 2016. 3. 3. 13:04

CoreLocation을 사용하게 되면 대략 다음과 같이 사용하게 된다.

- (void) startLocationManager {

    self.locationManager = [[CLLocationManager alloc] init];

    self.locationManager.delegate = self;

    [self.locationManager startUpdatingLocation];

}


- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    NSLog(@"didUpdateLocations");

}


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

    NSLog(@"didFailWithError");

}


iOS8에서는 위의 코드가 동작하지 않게 된다.

이유는 위치 정보를 사용하는 이유를 필수적으로 설정을 하여야 하는 문제가 있으며, 위치 정보에 대해서 상세히 설정 할 수 있게 되었다.

(항상 / App을 사용하는 동안 / 안 함)


iOS8이상부터 위치 정보를 사용하기 위해서는 Info.plist에 값을 넣어주어야 한다.

NSLocationAlwaysUsageDescription (항상 허용)

NSLocationWhenInUseUsageDescription (App을 사용하는 경우만 허용)


다음 그림과 같이 사용할 범위만 넣어주면 된다.





그리고 소스도 조금 변경되게 된다.


* App을 사용하는 경우에만 위치 정보 사용 요청할 경우


- (void) startLocationManager {

    self.locationManager = [[CLLocationManager alloc] init];

    self.locationManager.delegate = self;

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

[self.locationManager requestWhenInUseAuthorization];

}

    [self.locationManager startUpdatingLocation];

}


* 항상 허요하는 경우에 위치 정보 사용 요청할 경우


- (void) startLocationManager {

    self.locationManager = [[CLLocationManager alloc] init];

    self.locationManager.delegate = self;

if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {

[self.locationManager requestAlwaysAuthorization];

}

    [self.locationManager startUpdatingLocation];

}