Detect device orientation with CMMotionManager
What is it?
CMMotionManger ဆိုတာ Core Motion framework ရဲ့ class တစ်ခုဖြစ်ပါတယ်။ Hardware device ရဲ့ လှုပ်ရှားမှု(movement) တွေကို detect ဖြစ်ပြီး အလုပ်လုပ်နိုင်ဖို့ ထုတ်ထားပေးတဲ့ class ဖြစ်ပါတယ်။
The object for starting and managing motion services.
CMMotionManager ကနေ accelerometer, gyroscope, magnetometer နဲ့ devie-motion data လေးမျိုးကိုရနိုင်ပါတယ်။ ဒီ sensor data တွေကို live အနေနဲ့ constantly လည်းယူလို့ရသလို update interval တွေသတ်မှတ်ပြီးတော့လည်း collect လုပ်လို့ရပါတယ်။ CMMotionManager ကို app တစ်ခုလုံးမှာ instance တစ်ခုသာဆောက်ဖို့ Apple က recommend ပေးထားပါတယ်။ Instance တွေများနေရင် accelerometer နဲ့ gyroscope ရဲ့ data rate ကို ထိခိုက်စေနိုင်တယ်လို့ဆိုပါတယ်။ အသေးစိတ်ကိုသိချင်ရင်တော့ CMMotionManager doc မှာ သွားဖတ်ကြည့်လို့ရပါတယ်။
When to use it?
ကျွန်တော်တို့ ပုံမှန်ဆိုရင် device orientation ကို UIDevice.current.orientation နဲ့ယူလေ့ရှိကြပါတယ်။ ဒါပေမယ့် screen rotate လုပ်ခွင့်မပေးဘဲ landscape or portrait only သာခွင့်ပြုပြီး device orientation ကိုတော့ aware ဖြစ်စေချင်တယ်ဆိုတဲ့ use case မျိုးတွေရှိလာနိုင်ပါတယ်။
ဉပမာ ကျွန်တော်တို့ iPhone ရဲ့ camera app ကိုကြည့်မယ်ဆိုရင် AVCaptureVideoPreviewLayer က rotate မလုပ်ပါဘူး။ Portrait only နဲ့ဘဲ set up လုပ်ထားတာပါ။ ဒါပေမယ့် device ကို portrait ကနေ landscape ကို rotate လုပ်လိုက်တဲ့အခါ flashlight button တွေ back/selfie rotate button တွေက device orientation အတိုင်း လိုက် rotate လုပ်တာကိုတွေ့ရပါမယ်။
How to solve it?
ကျွန်တော်အောက်မှာ attach လုပ်ပေးထားတဲ့ gist ကို copy ကူးပြီး ကိုယ့် pj ထဲထည့်လိုက်ယုံပါဘဲ။ Code တွေက self-explainatory ဖြစ်တဲ့အတွက် အကျယ်ချဲ့ပြီးမရှင်းပြတော့ပါဘူး။
အောက်ပါအတိုင်း ပြန်ခေါ်သုံးနိုင်ပါတယ်။