본문 바로가기
아이폰 개발/ios 개념&튜토리얼

iOS CoreLocation 공통 모듈 - 싱글톤

by 인생여희 2021. 2. 9.

iOS CoreLocation 공통 모듈 - 싱글톤

 

 

1.CoreLocation 관련 라이브러리 추가

2.info.plist에 위치 동의관련 key value 값 입력

 

 

CoreLocation.h

 


#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface CoreLocation : NSObject <CLLocationManagerDelegate>

//CoreLocation 이 객체를 참조하는 카운터
@property (readwrite) NSInteger refNum;

//로케이션 매니져 전역 변수
@property (nonatomic, retain) CLLocationManager *locationManager;


//싱글톤 패턴
+(CoreLocation *) sharedSingleton;


//지정 초기화 메소드
-(id)initWithLocationManager;

@end

NS_ASSUME_NONNULL_END

 

 

 

CoreLocation.m

 



#import "CoreLocation.h"

@implementation CoreLocation

@synthesize locationManager , refNum;


//위치 정보 제공 객체 싱글턴 패턴으로 생성
+(CoreLocation *)sharedSingleton{
    
    static CoreLocation* sharedSington;
    if (!sharedSington) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedSington = [[CoreLocation alloc]initWithLocationManager];
        });
        
    }
    return sharedSington;
}


//지정 초기화 메소드
-(id)initWithLocationManager{
    
    self = [super init];
    
    if (self) {
        
        //참조 횟수 0 으로 초기화 => userdefalt로 변경하기
        refNum = 0;
        

        //초기화
        if (locationManager == nil) {
        
            NSLog(@"locationManager 초기화");
            
            locationManager = [[CLLocationManager alloc]init];             //초기화
            locationManager.desiredAccuracy = kCLLocationAccuracyBest;        //지도 정확도 최상
            locationManager.delegate = self;                            //델리게이트 설정
            
            locationManager.distanceFilter = 10;                         //기준위치 10 미터 기준
            locationManager.pausesLocationUpdatesAutomatically  = NO;        //자동 멈춤 방지
                        
            
        }
        
        
        //현지 지도 접근 권한
        CLAuthorizationStatus auth =  [CLLocationManager authorizationStatus];
        
        //아직 권한 결정이 안되었으면
        if (auth == kCLAuthorizationStatusNotDetermined) {
            
            //권한 요청
            [locationManager requestAlwaysAuthorization];                  //백그라운드에서도 접근할때 - 사용자 권한 동의
            //[locationManager requestWhenInUseAuthorization];                   //포그라운드에서만 접근할때 - 사용자 권한 동의
            
        //접근 권한이 허용일 경우
        }else if(auth == kCLAuthorizationStatusAuthorizedAlways ||
                auth == kCLAuthorizationStatusAuthorizedWhenInUse){
            
            [locationManager setAllowsBackgroundLocationUpdates:YES];       //백그라운드 업데이트 허용
            [locationManager startUpdatingLocation];                     //업데이트 시작
        }
    
    }
    
    return self;
}



//위치 접근 권한 상태 체크
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"allowed"); // allowed
    }
    else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"denied"); // denied
        
        if ([CLLocationManager locationServicesEnabled]){

            NSLog(@"Location Services Enabled");

        }
        
    }
}



//위치 업데이트 델리게이트 메소드
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    NSLog(@"위치 수집 업데이트 - didUpdateLocations");
    
    //NSLog(@"manager - latitude : %f" , manager.location.coordinate.latitude);
    //NSLog(@"manager - longitude : %f" , manager.location.coordinate.longitude);
    //NSLog(@"locationManager - latitude : %f" , locationManager.location.coordinate.latitude);
    //NSLog(@"locationManager - longitude : %f" , locationManager.location.coordinate.longitude);
    
}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    NSLog(@"위치 수집 오류 - didFailWithError");
}



#pragma helper Method
//권한 체크
- (void)checkLocationAccess {
    
    NSLog(@"checkLocationAccess");
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {

    // custom methods after each case

        case kCLAuthorizationStatusDenied:
            
            NSLog(@"kCLAuthorizationStatusDenied:");
            
            //[self allowLocationAccess]; // 커스텀 메소드 구현 필요
            
            break;
        case kCLAuthorizationStatusRestricted:
            
            NSLog(@"kCLAuthorizationStatusRestricted:");
            
           // [self allowLocationAccess]; // 커스텀 메소드 구현 필요
            
            break;
        case kCLAuthorizationStatusNotDetermined:
            
            NSLog(@"kCLAuthorizationStatusNotDetermined:");
            
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            
            NSLog(@"kCLAuthorizationStatusAuthorizedAlways:");
            
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            
            NSLog(@"kCLAuthorizationStatusAuthorizedWhenInUse:");
            
            break;
    }
}

@end




//위치 접근 권한
//https://stackoverflow.com/questions/50286742/handling-location-permission-in-ios-objective-c

 

 

 

위치접근 권한

stackoverflow.com/questions/50286742/handling-location-permission-in-ios-objective-c

 

세그 이용 화면 전환

http://minsone.github.io/mac/ios/ios-using-segue-of-storyboard

 

ios 화면 전환

https://twih1203.medium.com/swift-ios-%ED%99%94%EB%A9%B4%EC%A0%84%ED%99%98%ED%95%98%EA%B8%B0-5e5998679d3a