Notice
Recent Posts
Recent Comments
Link
투케이2K
13. (ios/swift) 실시간 비콘 beacon 신호 활성 실시 본문
[개발 환경 설정]
개발 툴 : XCODE
개발 언어 : SWIFT
[방법 설명]
[소스 코드]
import UIKit
import AVFoundation
import Photos
import CoreLocation
import CoreBluetooth
// [CLLocationManagerDelegate 추가 필요]
class MainController: UIViewController, CBPeripheralManagerDelegate {
// [MainController : 버튼 UI 객체 정의 실시]
@IBOutlet weak var intentBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print("")
print("===============================")
print("[MainController > viewDidLoad() : 뷰 로드 실시]")
print("===============================")
print("")
// [블루투스 권한 설정 퍼미션 확인 실시]
self.checkBluePermission()
}
/*
[블루투스 사용 권한 요청]
필요 : import CoreBluetooth
*/
var centralManager: CBCentralManager!
func checkBluePermission(){
print("")
print("===============================")
print("[MainController > checkBluePermission() : 블루투스 사용 권한 요청 실시]")
print("===============================")
print("")
self.centralManager = CBCentralManager(delegate: self, queue: nil)
}
// [실시간 비콘 신호 활성 진행]
var startBeaconSendFlag = false // 비콘 신호 활성 진행 플래그 값
var beaconSendCount = 1 // 비콘 신호 활성 시간
// [비콘 설정 셋팅 : 설정한 uuid , major , minor 값을 가지고 실시간 비콘 신호 활성]
let uuid = UUID(uuidString: "F7A3E806-F5BB-43F8-BA87-0783669EBEB1")!
let major : CLBeaconMajorValue = 123
let minor : CLBeaconMinorValue = 456
// [특정 uuid , major, minor 일치 값 설정]
var beaconRegion: CLBeaconRegion!
var beaconPeripheralData: NSDictionary!
var peripheralManager: CBPeripheralManager!
func startBeaconSend() {
// [비콘 신호 활성이 진행 되지 않은 경우 확인]
if self.startBeaconSendFlag == false {
print("")
print("===============================")
print("[MainController > startBeaconSend() : 실시간 비콘 신호 활성 시작]")
print("===============================")
print("")
// [비콘 신호 활성 값 설정 실시]
self.beaconRegion = CLBeaconRegion.init(uuid: self.uuid, major: CLBeaconMajorValue(self.major), minor: CLBeaconMinorValue(self.minor), identifier: self.uuid.uuidString)
self.beaconPeripheralData = self.beaconRegion.peripheralData(withMeasuredPower: nil)
self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
// [비콘 신호 활성 플래그 값 지정 실시]
self.startBeaconSendFlag = true
// [비콘 신호 활성 시간 체크 타이머 동작 실시]
self.startTimer()
}
else {
print("")
print("===============================")
print("[MainController > startBeaconSend() : 실시간 비콘 활성 시작 [이미 진행 중]]")
print("===============================")
print("")
}
}
func stopBeaconSend() {
print("")
print("===============================")
print("[MainController > stopBeaconSend() : 실시간 비콘 신호 활성 종료]")
print("===============================")
print("")
// [비콘 신호 활성을 진행한 경우 확인]
if self.startBeaconSendFlag == true {
// [비콘 신호 활성 종료]
self.peripheralManager.stopAdvertising()
// [변수값 초기화 실시]
//self.peripheralManager = nil
//self.beaconPeripheralData = nil
//self.beaconRegion = nil
// [비콘 신호 활성 플래그값 초기화]
self.startBeaconSendFlag = false
// [비콘 신호 활성 시간 초기화]
self.beaconSendCount = 1
}
}
// [실제로 비콘 신호 활성 수행 부분]
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
// [블루투스 활성 상태 체크 실시 및 비콘 신호 활성]
if peripheral.state == .poweredOn {
self.peripheralManager.startAdvertising(beaconPeripheralData as? [String: Any])
print("")
print("===============================")
print("[MainController > peripheralManagerDidUpdateState() : 블루투스 활성 상태 >> 실시간 비콘 신호 활성 성공]")
print("uuid : ", self.uuid)
print("major : ", self.major)
print("minor : ", self.minor)
print("===============================")
print("")
}
else if peripheral.state == .poweredOff {
print("")
print("===============================")
print("[MainController > peripheralManagerDidUpdateState() : 블루투스 비활성 상태 >> 실시간 비콘 신호 활성 실패]")
print("===============================")
print("")
self.peripheralManager.stopAdvertising()
}
}
// [실시간 반복 작업 시작 호출]
var timer : Timer?
func startTimer(){
print("")
print("===============================")
print("[MainController > startTimer : 비콘 신호 활성 타이머 동작 시작]")
print("===============================")
print("")
// [타이머 객체 생성 실시]
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCallback), userInfo: nil, repeats: true)
}
// [실시간 반복 작업 수행 부분]
@objc func timerCallback() {
print("")
print("===============================")
print("[MainController > timerCallback : 비콘 신호 활성 타이머 동작 진행]")
print("[beaconScanCount : \(beaconSendCount)]")
print("===============================")
print("")
// [처리할 로직 작성 실시]
self.beaconSendCount += 1 // 1씩 카운트 값 증가 실시
if self.beaconSendCount > 10 { // 카운트 값이 10인 경우
self.stopTimer() // 타이머 종료 실시
}
}
// [실시간 반복 작업 정지 호출]
func stopTimer(){
print("")
print("===============================")
print("[MainController > stopTimer : 비콘 신호 활성 타이머 동작 종료]")
print("===============================")
print("")
// [실시간 반복 작업 중지]
if self.timer != nil && self.timer!.isValid {
self.timer!.invalidate()
self.stopBeaconSend() // 비콘 신호 활성 종료 호출
}
}
// [애플리케이션 설정창 이동 실시 메소드]
func intentAppSettings(content:String){
// 앱 설정창 이동 실시
let settingsAlert = UIAlertController(title: "권한 설정 알림", message: content, preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "확인", style: .default) { (action) in
// [확인 버튼 클릭 이벤트 내용 정의 실시]
if let url = URL(string: UIApplication.openSettingsURLString) {
print("")
print("===============================")
print("[MainController > intentAppSettings() : 앱 설정 화면 이동]")
print("===============================")
print("")
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
settingsAlert.addAction(okAction) // 버튼 클릭 이벤트 객체 연결
let noAction = UIAlertAction(title: "취소", style: .default) { (action) in
// [취소 버튼 클릭 이벤트 내용 정의 실시]
return
}
settingsAlert.addAction(noAction) // 버튼 클릭 이벤트 객체 연결
// [alert 팝업창 활성 실시]
present(settingsAlert, animated: false, completion: nil)
}
}
// [블루투스 상태 체크 실시]
extension MainController: CBCentralManagerDelegate {
// [블루투스 상태 및 권한 부여 확인 실시]
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 상태 알수 없음]")
print("===============================")
print("")
case .resetting:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 서비스 리셋]")
print("===============================")
print("")
case .unsupported:
print("")
print("===============================")
print("[MainController > CBCentralManager : 기기가 블루투스를 지원하지 않습니다]")
print("===============================")
print("")
case .unauthorized:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 사용 권한 확인 필요]")
print("===============================")
print("")
// [앱 블루투스 권한 사용 설정창 이동]
self.intentAppSettings(content: "블루투스 사용 권한을 허용해주세요")
case .poweredOff:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 비활성 상태]")
print("===============================")
print("")
// [자동으로 시스템에서 비활성 상태 알림 및 팝업창 호출 실시]
case .poweredOn:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 활성 상태]")
print("===============================")
print("")
// [실시간 비콘 신호 활성 실시]
self.startBeaconSend()
@unknown default:
print("")
print("===============================")
print("[MainController > CBCentralManager : 블루투스 CASE DEFAULT]")
print("===============================")
print("")
}
}
}
[결과 출력]
반응형
'IOS' 카테고리의 다른 글
15. (ios/swift) 외부 링크 웹 사이트 이동 실시 - URL , SFSafariViewController (0) | 2021.10.20 |
---|---|
14. (ios/swift) http 통신 get , post , post body json 요청 실시 - URLSession (0) | 2021.10.19 |
12. (ios/swift) 실시간 비콘 beacon 목록 스캔 실시 (4) | 2021.10.18 |
11. (ios/swift) 실시간 블루투스 목록 스캔 실시 - bluetooth scan (0) | 2021.10.17 |
10. (ios/swift) 퍼미션 권한 요청 수행 실시 - info , permission (0) | 2021.10.17 |
Comments