제2외국어/iOS

[iOS] Multitasking : Location

윈플. 2013. 1. 29. 09:34

다음은 iOS Multitasking 중에서 Location입니다.


-- 프로젝트 설정

먼저 CoreLocation.framework 추가하기



그리고 Audio와 마찬가지로 .plist 설정




자 이제 소스부분입니다.

백그라운드에서 동작하게 하기 위해 AppDelegate.h / .m 에서 작업을 시작합니다.


1. import, 변수 선언

 #import <CoreLocation/CoreLocation.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;



2. init & 설정

혹시나 AppDelegate에 있는 함수들이 정확히 무슨 기능을 하시는지 모르시는 분은 더보기를 통해 확인하시기 바랍니다.


먼저 앱시작하면 제일 먼저 들어오는 함수에서 locationManager를 초기화 및 정확도를 설정합니다.
그리고 startUpdating 을 시작합니다.
( Location은 위치이며, Heading은 방향을 알수있습니다. )


- (BOOL)application:(UIApplication *)application
   didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

   /* 
    locationManager 생성
    delegate 연결
    정확도에 대한 설정 
   */

     locationManager = [[CLLocationManager alloc]init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];

    // AutoPause API 비활성화
    // 기본적으로 활성화(YES) 되어있음
    [locationManager setPausesLocationUpdatesAutomatically:NO]; 
     

    // LocationManager update
    [
locationManager startUpdatingLocation];
    [locationManager startUpdatingHeading];

     return YES;

}

** AutoPause API ??

- AutoPause API 활성화
- 움직이지 않을 때는 업데이트를 하지 않음
- CLLocationManager 는 기본적으로 AutoPause API가 활성화 상태
- AutoPause API를 사용하지 않으려면 pausesLocationUpdatesAutomatically 를 통해 설정
( YES : 활서 | NO : 비활성 )
 <단점>
- AutoPause API를 비활성화를 한다면 확실히 Requset가 많이 발생하고 그만큼 베터리 소모량이 큽니다


다음으로 Background 진입 시에 위치가 변하는 것을 모니터링 하는 함수를 호출합니다.

 

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    // 앱이 Background 진입 호출
    NSLog(@"Background");    

    // locationManager 위치가 변하는 것을 모니터링 시작하는 함수
    [locationManager startMonitoringSignificantLocationChanges];   

}

마지막으로 앱이 종료되면, 그리고 실행 중일 때는 locationManager를 멈추는 작업을 해줍시다.

 
- (void)applicationDidBecomeActive:(UIApplication *)application
{

    // Active 상태로   호출
    NSLog(@"Become");

    [locationManager stopMonitoringSignificantLocationChanges];
}


- (void)applicationWillTerminate:(UIApplication *)application
{

    // 앱이 종료될 호출
    // locationManager 멈춤
    NSLog(@"terminate");
    [locationManager stopMonitoringSignificantLocationChanges];

}
 




3. (중요) Location Delegate 부분입니다. 

didUpdateLocations Delegate 함수를 통해, 현재 상태가 백그라운드 상태에 있을 경우에만 업데이트 되고 Log를 찍게
했습니다.
( 백그라운드 상태가 아니라면 실행안됩니다. )

#pragma mark Locationmanager delegate

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

    BOOL isInBackground = NO;    

    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
   {
        isInBackground = YES; 
        NSLog(@"update location : %f, %f",manager.location.coordinate.latitude,
                                                             manager.location.coordinate.longitude);

    }    

} 



4. 실행결과

이 앱에게 위치정보를 허락하는 부분, 당연히 OK

앱 실행시킨 화면입니다.
당연히 암것도 없고, 아무것도 안 찍힙니다.


여기서 홈버튼을 누르게 되면, Become 상태에서 Background상태로 변하면서 Log가 찍히는걸 알 수 있습니다.
다시 앱으로 들어온다면 다시 Become상태로 되면서 업데이트 종료  :)




PS.

시뮬레이터에서는 끊임없이 작동이 되지만, 실제로 디바이스에서는 이상하게 2~3번 정도 로그가 찍히다가 멈춥니다. 
( 실제로는 멈춘게 아닙니다. )
iOS에서는 기본적으로 사용자가 활동하지 않을때! 즉 움직이지 않을때는 위치 업데이트를 중지합니다. 


** 간단하게 웹디비에 연결해서 실제 밥먹으로 돌아다니면서 테스트 결과, 주기적으로 업데이트를 합니다. 

( 위치가 거의 변하지 않더라도, 적어도 30분에 한번씩은 업데이트를 꼭 합니다! )


< 참고 문서 >
CLLocationManager Class Reference

'제2외국어 > iOS' 카테고리의 다른 글

[iOS]통화하기  (0) 2013.05.29
[iOS]Font 관련하여..  (0) 2013.04.26
[iOS] Multitasking : Audio  (0) 2013.01.24
About : iOS Multitasking  (0) 2013.01.21
[ios] 서버에 이미지만 보낼 때와 이미지 + 정보를 보낼 때  (0) 2013.01.04