티스토리 뷰

반응형

 

기록차 남겨둠

# 문제

WKInterfaceDevice.current().play(.start)

를 사용하여 Haptic feedback을 실행하도록 했으나

1. 앱이 켜저있는 상태에서 화면이 꺼지거나

2. background로 들어가면

Haptic feedback이 정지되는 이슈.

 

# 첫번째 방법 - Session Type이용하기(Time limit있음) 

watchKit Extension Target > capability > Background Modes를 추가.

세션타입을 결정해야하는데, 요건 Extended runtime sessions이라고 부르는 것 같다. 요걸 사용하면 

시계 화면이 꺼진 후에도 앱이 블루투스 기기와 계속 통신하고 데이터를 처리하거나, 사운드 또는 햅틱을 재생할 수 있다고 한다.

 


문서를 보면, 세션타입에는 다음과 같은 것들이 있다. 

[self-care]

비교적 간단한 활동을 통해 사용자를 가이드. 이러한 활동은 양치질과 같은 사용자의 정서적 웰빙 또는 건강에 중점을 둔다. 

[mindfulness]

조용한 명상을 위해 확장된 런타임 세션을 활성화.

걷기 명상의 경우 HKWorkoutSession을 사용하는 것이 좋음

마찬가지로 앱이 전체 명상 세션 동안 오디오를 재생하는 경우 WKExtendedRuntimeSession을 사용할 이유가 없음

[physical-therapy]

스트레칭, 강해지기(strengthening), motion 운동을 위한 확장된 런타임 세션을 활성화.

물리 치료 활동이 엄격한 경우(ex. 운동용 자전거 타기) HKWorkoutSession을 사용하는 것이 좋음. 

[smart alarm]

사용자의 심박수와 움직임을 모니터링 할 시간을 예약. 

앱은 이 정보를 사용하여 알람을 재생하기위한 최적의 시간을 결정하며, 일반적으로 사용자를 잠에서 깨움. 

[workout-processing]

active workout 세션을 백그라운드에서 실행 할 수 있음.

 

🙋 : workout-processing은 세션타입에 없는데..? 

🧑‍💻 : 요기있음. 

extended(확장된) 세션타입은 self-care, mindfulness, physical-therapy, smart alarm이렇게 4개중 한개만 활성화 할 수 있는게 맞음. 

하지만 extended 세션타입과 workout-processing 모두를 활성화 할 수 있음. 

이렇게.

 

🙋 : 난 뭐 명상, 운동도 아니고..1) 화면이 꺼져도 2) 앱이 backgorund에 내려가도 Haptic feedback을 재생시키고 싶어.

🧑‍💻 : 

1) 앱이 켜진 상태. 즉 foreground에 올라와있는 상태에서 화면이 꺼진 상태에서도 Haptic feedback을 재생시키고 싶다면 

Self-care, Mindfulness로도 충분하다.

하지만 크라운을 눌러서 명시적으로 background로 나가거나 다른앱으로 전환하면 Haptic feedback은 꺼지게 된다. 

2) Background상태에서도 Haptic feedback을 계속 재생시키고 싶다면 Pysical therapy, Smart alarm중 하나를 선택해야한다. 


이걸 선택한다고 바로 되는것은 아니고,

private var session = WKExtendedRuntimeSession()

// 세션 시작
session.start()

// 세션 종료
session.invalidate()

// WKExtendedRuntimeSessionDelegate
session.delegate = self

// MARK:- Extended Runtime Session Delegate Methods
func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
    // Track when your session starts.
}

func extendedRuntimeSessionWillExpire(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
    // Finish and clean up any tasks before the session ends. 
}
    
func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession, didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?) {
    // Track when your session ends.
    // Also handle errors here.
}

세션을 만들고 start를 해줘야한다. 

이렇게하면 화면이 꺼져도, Background로 내려가도 Haptic feedback이 잘 작동하게 된다.

세션이 시작하고 끝나는 이벤트를 감지해서 뭔가를 하고싶다면 WKExtendedRuntimeSessionDelegate를 채택하면 된다. 난 패스..,

 

🙋 : Time limit? 

🧑‍💻 : 세션은 계속 유지되는것이 아니라 Time limit이 있다..이 시간이 지나면 세션이 종료되게 된다. 

→ 자연스럽게 Haptic Feedback역시 종료되겠지...??? 

 

# 두번째 방법 - HKWorkoutSession 이용하기

watchOS Haptic Feedback play메소드 문서 에서도 

By default, you cannot play haptic feedback in the background. The only exception are apps with an active workout session. For more information, see Run in the Background  in HKWorkoutSession.

이렇게 나와있으니..HKWorkoutSession을 이용해보자. 

1. capability에서 HealthKit추가

2. Backgrond Modes의 audio와 workout processing on

3.

import HealthKit

private let healthStore = HKHealthStore()
private var session: HKWorkoutSession?
private let configuration = HKWorkoutConfiguration()

configuration.activityType = .running
configuration.locationType = .outdoor

do {
   self.session = try HKWorkoutSession(healthStore: healthStore, configuration: configuration)
} catch {
   return
}
// 시작
session?.startActivity(with: Date())

// 종료
session?.stopActivity(with: Date())

 이렇게 하면 세션타입없이 == Time limit없이!! Background에서 Haptic Feedback을 재생할 수 있다. 

 

🧑‍💻 : 아니 그럼 Time limit없는 얘가 짱이네...처음부터 HKWorkoutSession만 알려주지..

오른쪽 하단 달리는 애니메이션

🙋 : 처음에 알려준 Session Type으로 할때는.. 앱을 Background로 보내고 페이스(?)로 돌아왔을 때 저 애니메이션이 없는데

HKWorkoutSession로 하게 되면 저렇게 달리는 애니메이션이 재생된다. 말그대로 Workout을 시작하게 해서 그런듯...ㅎ

이게 마음에 안들어서 그냥 Session Type으로 할 예정. 제공하는 Time limit이 충분할 것 같기도 하고 ㅎㅎ..!!!

끝!

 

참고 : 

https://developer.apple.com/documentation/watchkit/wkinterfacedevice/1628128-play

https://developer.apple.com/documentation/watchkit/background_execution

https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/running_workout_sessions#2317537

https://developer.apple.com/documentation/watchkit/using_extended_runtime_sessions

 

반응형

'watchOS' 카테고리의 다른 글

watchOS ) Table구성하는 법  (1) 2021.03.27