iOS/Objective-C) CoreBluetooth 간단하게 블루투스 상태 확인하기

FITF-·2022년 7월 21일
0
post-thumbnail

오브젝트 씨, 블루투스 상태 확인해보기

간단하게 블루투스가 켜져있는지, 꺼져있는지 상태를 알아보는 코드를 정리해봅니다.

먼저 ViewController.h 에 작성한 코드

// ViewController.h


#import <UIKit/UIKit.h>
#import <CoreBluetooth/CoreBluetooth.h>


@interface ViewController : UIViewController

@property (nonatomic, strong) CBCentralManager *bluetoothManager;


- (void)centralManagerDidUpdateState:(CBCentralManager *)central;

@end

그 다음은 ViewController.m 에 작성한 코드

// ViewController.m


#import "ViewController.h"


@interface ViewController ()

@end


@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  
  if(!self.bluetoothManager)
  {
      NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @NO};
      self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:options];
  }
}



- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;


    switch(self.bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;

        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;

        default: stateString = @"State unknown, update imminent."; break;
    }

    NSLog(stateString); 
    // -> 로그에서 상태 메시지로 블루투스 연결 확인 가능 "Bluetooth is currently powered off." 이런 식으로 위 상태마다 출력되는 메시지를 로그에서 블루투스를 껐다 킬때마다 확인 할 수 있음
}
@end  

위와 같은 코드를 작성 후 빌드하면 연결된 아이폰 화면에는 아무것도 없는 까만 화면이 나타납니다.

Xcode의 로그창을 봐주세요. 만약 현재 블루투스가 켜져있는 상태라면 아래와 같은 로그를 확인할 수 있습니다.

그 상태에서 블루투스를 끄면 아래와 같이 꺼졌다는 로그 메세지를 확인할 수 있습니다.

에러

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSBluetoothAlwaysUsageDescription key with a string value explaining to the user how the app uses this data.

위와 같은 메세지가 뜨며 실행이 되지 않는다면,

Privacy - Bluetooth Always Usage Description

캡처처럼 (Info의 마지막 줄 key 값) 위 메세지를 Key 자리에 추가해주면 됩니다. 마우스를 갖다 대면 +,- 표시가 나타납니다. + 표시를 눌러서 새로운 row 추가 후 key 값에 저 메세지를 복붙하고 다시 빌드하면 제대로 작동합니다.

profile
iOS 개발자 | SwiftUI

0개의 댓글