투케이2K

122. (Objective-C/objc) CLLocationManager didRangeBeacons 사용해 실시간 비콘 (beacon) 스캔 수행 실시 본문

Objective-C

122. (Objective-C/objc) CLLocationManager didRangeBeacons 사용해 실시간 비콘 (beacon) 스캔 수행 실시

투케이2K 2022. 10. 27. 19:12
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : OBJECTIVE-C

 

[사전 info.plist 설정]

 

[ViewController.h : 소스 코드]

// MARK: - [import 정의]
#import <UIKit/UIKit.h>
#import <SafariServices/SafariServices.h>
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>


// MARK: - [위치 권한 import]
#import <CoreLocation/CoreLocation.h>


@interface ViewController : UIViewController <CLLocationManagerDelegate> { // [클래스 딜리게이트 정의]
    
    /*
     -----------------------------
     // [지역 변수 정의]
     -----------------------------
     1. self 키워드 없이 접근 가능
     -----------------------------
     2. 메소드 내에서 사용 필요
     -----------------------------
     3. 정보 은닉 데이터 처리
     -----------------------------
     */
    
}


// [get set 프로퍼티 선언]
@property (strong, nonatomic) CLLocationManager *locationManager; // [위치 상태]




@end
 

[ViewController.m : 소스 코드]

// MARK: - [뷰 컨트롤러 헤더 파일 import]
#import "ViewController.h"


// MARK: - [전처리 지시어 헤더 파일 import]
#import "S_Define.h"


// MARK: - [프로젝트-Swift.h import 명시]
#import "objectiveProject-Swift.h"


// MARK: - [클래스 @interface]
@interface ViewController(){
    
}
@end


// MARK: - [클래스 @implementation]
@implementation ViewController{
    
}


// MARK: [클래스 헤더 파일에 선언 한 property 속성 지정]
@synthesize locationManager; // [위치 상태]






// MARK: - [뷰 로드 실시]
- (void)viewDidLoad {
    [super viewDidLoad];
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> viewDidLoad() :: 뷰 로드 실시] \n");
    printf("==================================== \n");
    printf("\n");
}





// MARK: - [뷰 로드 완료]
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> viewWillAppear() :: 뷰 로드 완료] \n");
    printf("==================================== \n");
    printf("\n");
}





// MARK: - [뷰 화면 표시]
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> viewDidAppear() :: 뷰 화면 표시] \n");
    printf("==================================== \n");
    printf("\n");
    
    // [테스트 메인 함수 호출]
    [self testMain];
}





// MARK: - [뷰 정지 상태]
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> viewWillDisappear() :: 뷰 정지 상태] \n");
    printf("==================================== \n");
    printf("\n");
}





// MARK: - [뷰 종료 상태]
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> viewDidDisappear() :: 뷰 종료 상태] \n");
    printf("==================================== \n");
    printf("\n");
}





// MARK: - [헤더 파일에 정의 없이 : void 메소드 구현]
- (void)testMain {
    printf("\n");
    printf("==================================== \n");
    printf("[ViewController >> testMain() :: 테스트 메소드 수행] \n");
    printf("==================================== \n");
    printf("\n");

    
    // [try catch 구문 정의 실시]
    @try {
        
        dispatch_async(dispatch_get_main_queue(), ^{
                    
            // [CLLocationManager 인스턴스 할당 실시]
            self.locationManager = [[CLLocationManager alloc] init];
            
            
            // [딜리게이트 지정]
            self.locationManager.delegate = self;
            
            
            // [거리 정확도 설정]
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            
            
            // [위치 권한 설정 값 확인]
            [self.locationManager requestAlwaysAuthorization];
            
            
            // [위치 업데이트 시작]
            [self.locationManager startUpdatingLocation];

            
        });

    }
    @catch (NSException *exception) {
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> catch :: 예외 상황 확인] \n");
        printf("[name :: %s] \n", exception.name.description.UTF8String);
        printf("[reason :: %s] \n", exception.reason.description.UTF8String);
        printf("==================================== \n");
        printf("\n");
    }
}






// MARK: - [앱 상태 바 콘텐츠 색상 커스텀 변경 실시]
-(UIStatusBarStyle)preferredStatusBarStyle {
    // return UIStatusBarStyleLightContent; // [상태바 콘텐츠 색상 흰색으로 변경 : ex (배터리 표시)]
    if (@available(iOS 13.0, *)) { // [상태바 콘텐츠 색상 검정색으로 변경 : ex (배터리 표시)]
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}





// MARK: - [위치 권한 부여 상태 확인 딜리게이트]
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    if (status == kCLAuthorizationStatusAuthorizedAlways){
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: kCLAuthorizationStatusAuthorizedAlways] \n");
        printf("[message :: 위치 사용 권한 항상 허용] \n");
        printf("==================================== \n");
        printf("\n");
        
        // [비콘 스캔 실시]
        [self startBeaconScan];
    }
    else if (status == kCLAuthorizationStatusAuthorizedWhenInUse){
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: kCLAuthorizationStatusAuthorizedWhenInUse] \n");
        printf("[message :: 위치 사용 권한 앱 사용 시 허용] \n");
        printf("==================================== \n");
        printf("\n");
        
        // [비콘 스캔 실시]
        [self startBeaconScan];
    }
    else if (status == kCLAuthorizationStatusDenied){
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: kCLAuthorizationStatusDenied] \n");
        printf("[message :: 위치 사용 권한 거부] \n");
        printf("==================================== \n");
        printf("\n");
    }
    else if (status == kCLAuthorizationStatusRestricted){
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: kCLAuthorizationStatusRestricted] \n");
        printf("[message :: 위치 사용 권한 제한 상태] \n");
        printf("==================================== \n");
        printf("\n");
    }
    else if (status == kCLAuthorizationStatusNotDetermined){
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: kCLAuthorizationStatusNotDetermined] \n");
        printf("[message :: 위치 사용 권한 대기 상태] \n");
        printf("==================================== \n");
        printf("\n");
    }
    else {
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> locationManager :: 위치 권한 부여 상태 확인] \n");
        printf("[status :: else] \n");
        printf("==================================== \n");
        printf("\n");
    }
}






// MARK: - [비콘 스캔 시작 실시 부분]
- (void)startBeaconScan {
    
    // [스캔을 수행할 비콘 UUID 선언 실시]
    NSString *uuidString = @"F7A3E806-F5BB-43F8-BA87-0783669EBEB1";
    
    
    // [비콘 거리 측정 가능 여부 체크]
    if ([CLLocationManager isRangingAvailable]) {
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> startBeaconScan() :: 비콘 스캔 시작] \n");
        printf("==================================== \n");
        printf("\n");
        
        // [비콘 스캔 시작]
        NSUUID *beaconUuid = [[NSUUID UUID] initWithUUIDString:uuidString];
        
        CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc]
                                            initWithProximityUUID:beaconUuid
                                            identifier:uuidString];

        [self.locationManager startMonitoringForRegion:beaconRegion];
        [self.locationManager startRangingBeaconsInRegion:beaconRegion];
        
    } else {
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> startBeaconScan() :: 비콘 스캔 에러] \n");
        printf("[error :: 비콘 거리 측정 불가능 디바이스] \n");
        printf("==================================== \n");
        printf("\n");
    }
}





// MARK: - [비콘 스캔 시 호출]
- (void)locationManager:(CLLocationManager *)manager
        didRangeBeacons:(NSArray *)beacons
               inRegion:(CLBeaconRegion *)region {
    
    if (beacons.count > 0){
        
        for (CLBeacon *beacon in beacons){
            printf("\n");
            printf("==================================== \n");
            printf("[ViewController >> didRangeBeacons() :: 실시간 비콘 스캔 확인] \n");
            printf("[uuid :: %s] \n", beacon.proximityUUID.description.UTF8String);
            printf("[major :: %s] \n", beacon.major.description.UTF8String);
            printf("[minor :: %s] \n", beacon.minor.description.UTF8String);
            printf("==================================== \n");
            printf("\n");
        }
    }
    else {
        printf("\n");
        printf("==================================== \n");
        printf("[ViewController >> didRangeBeacons() :: 실시간 비콘 스캔 없음] \n");
        printf("==================================== \n");
        printf("\n");
    }
}


// --------------------------------------
@end
// --------------------------------------
 

[결과 출력]


 

반응형
Comments