Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: 포착 블루투스 기능 - 내 주변 포착 유저 탐색 #130

Open
wants to merge 47 commits into
base: develop
Choose a base branch
from

Conversation

syhwang1231
Copy link
Collaborator

💌 작업한 내용

  • 주변에 있는 포착 유저 탐색 - with 블루투스
  • 탐색된 유저의 위치 랜덤 배정
  • 내주변포착을 통해 포착하는 경우 태그 리스트에서 해당 유저 고정
  • 백그라운드에서 일정 시간마다 기기 탐색하는 태스크를 넣고 탐색하기 → 탐색되면 푸시 알림 전송

💭 PR POINT

  • 백그라운드 동작
  1. 앱의 launch sequence가 끝나기 전에 background task를 스케쥴러에 등록 (미리)
// AppDelegate.swift
private func registerBackgroundTasks() {
        print("[AppDelegate] Background Task 등록!")
        // 1. Refresh Task 등록
        let taskIdentifier = ["NearbyPochak"]
        
        BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier[0], using: nil, launchHandler: { task in
            // 2. 실제로 수행할 Background 동작 구현
            self.handleBackgroundTask(task: task as! BGAppRefreshTask)
            print("do backgroundtask")
        })
    }
  1. 실제 백그라운드 상태에 들어갔을 때 수행할 task 구현
// AppDelegate.swift

/// Background에서 수행할 task를 구현
    /// - Parameter task: BGTaskScheduler에 등록한 task
    private func handleBackgroundTask(task: BGAppRefreshTask) {
        let operationQueue = OperationQueue()
        
        scheduleBackgroundTask()  // 다음 백그라운드 작업 예약
        
        print("[AppDelegate] Background task 수행 중")
        
        let operation = BluetoothRefreshOperation()
        
        // Background Task가 갑자기 종료되거나 TimeOut될 때를 대비
        task.expirationHandler = {
//            task.setTaskCompleted(success: false)  // task가 완료되었음을 알려줌 (백그라운드 자원 이용 stop)
//            operation.cancel()
            // After all operations are cancelled, the completion block below is called to set the task to complete.
            operationQueue.cancelAllOperations()
        }
        
        operation.completionBlock = {
            // 백그라운드 작업 스케줄러에게 작업 완료됨 알리기
            task.setTaskCompleted(success: !operation.isCancelled)
            BluetoothSerialManager.shared.stopScan()
            print("[AppDelegate] Background task completed with Success: \(!operation.isCancelled)")
        }
        
        // 실행 대기열에 추가 -> 비동기로 실행
        operationQueue.addOperation(operation)
    }
  1. 태스크 수행 후 다음 태스크 예약
// AppDelegate.swift

func scheduleBackgroundTask() {
        let task = BGAppRefreshTaskRequest(identifier: "NearbyPochak")
        task.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)  // 지금부터 15분을 넘지 않는 시간 내에 실행
        
        do {
            try BGTaskScheduler.shared.submit(task)  // Background Task 등록!!
            print("[AppDelegate] Background Task submitted!")
        } catch {
            print("[!] Error - Could not schedule app refresh: \(error)")
        }
    }

3-1. 실제 백그라운드 상태에 진입했을 때 scheduleBackgroundTask() 호출

// SceneDelegate.swift

func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
        
        (UIApplication.shared.delegate as? AppDelegate)?.scheduleBackgroundTask()
    }

📷 스크린샷

구현 내용 스크린샷
내주변포착으로 포착
  • 서서히 나타나는 애니메이션
RPReplay_Final1739366336.MP4

💐 관련 이슈

@syhwang1231 syhwang1231 added ✨ feat 새로운 기능 🍀 수연 저에여 labels Feb 12, 2025
@syhwang1231 syhwang1231 self-assigned this Feb 12, 2025
@@ -12,7 +12,8 @@ struct APIConstants{
static let baseURLv2 = "http://15.165.84.249"

// MARK: - Feature URL
// login...

static let memberProfileImgBaseURL = "https://storage.googleapis.com/pochak-image-bucket/member/"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 baseURL은 어디에서 온 건가요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

프로필 이미지 url까지 블루투스 데이터로 쏘게 되면 아예 이 기능 자체가 작동을 안해서, "memberProfileImgBaseURL(handle)" 이런 식으로 base되는 url 뒤에 사용자 핸들만 넣으면 프로필 이미지에 접근할 수 있도록 서버 쪽에서 프로필 이미지 base url을 픽스해줬어요!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ feat 새로운 기능 🍀 수연 저에여
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feat] 포착 블루투스 기능
2 participants