Fix Orientation and list for changes - SWIFT
Shawn, thanks for the advice. In the end, that's what I did. Here's my code
You'll also need to import CoreMotion
var motion = CMMotionManager()
var currentOrientation: String = "Portrait"
func oritentationUpdateStart() {
motion.accelerometerUpdateInterval = 1.0
motion.startAccelerometerUpdates(to: OperationQueue.current! ) { (data, error) in
if let accel = data {
if (accel.acceleration.x > 0.5){
self.currentOrientation = "Upsidedown Landscape"
}
else if (accel.acceleration.y > 0.5) {
self.currentOrientation = "Upsidedown Portrait"
}
else if (accel.acceleration.x < -0.5) {
self.currentOrientation = "Landscape"
}
else if (accel.acceleration.y < -0.5) {
self.currentOrientation = "Portrait"
}
}
}
}
Better way than using a var outside a func to track device orientation?
After considerable research and testing, I found that the most reliable way to do this (AFAIK) was to keep the global var but to use the CGSize that is being passed as a means of testing. It's immediately available whereas orientation might not yet be set. Quickly rotating or flipping the device would cause errors with the latter. I was not able to trigger an error when using size as shown here:
var previousSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if size == previousSize {return}
else{ previousSize = size}
let aspectRatio = Float(size.height/size.width)
mapViewC.height = mapViewC.height / aspectRatio
}
cannot force app to portrait-only in iOS9
Please check Info.plist for "Supported interface orientations".
It must show Portrait for your requirement. Sometimes it is not updated as project settings in General Tab. If you find landscape orientation over here then remove it.
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
Related Topics
Alert When New Version of iOS App Is Available
Fonts Not Displaying in Interface Builder
Apple Watch - Only Getting Data If App on Phone Is Active
How to Change a Swiftui Color to Uicolor
Finding Distance Between Cllocationcoordinate2D Points
How to Add Custom Text in Nsdateformatter's Format String
Com.Facebook.Sdk Error 2 on iOS
Xcode 5/iOS 7 - Localization Not Working in Simulator
Using Sysctlbyname() from Swift
Apple MACh-O Linker (Id) Warning:Building for MACosx, But Linking Against Dylib Built for iOS
Uitableviewcellaccessorycheckmark and Autolayout Constraints
Programmatically Highlight Uibarbuttonitem
Optional Binding Succeeds If It Shouldn'T
How to Ensure to Run Some Code on Same Background Thread
Cameranode Rotate as iOS Device Moving
How to Mute/Unmute Audio When Playing Video Using Mpmovieplayercontroller