我正在尝试创建一个应用程序(在swift中),它将检测iPhone是否处于运动状态。
我怎么去接近这个?
答案 0 :(得分:3)
您应该考虑从加速度计获取数据。
以下是如何检索信息的示例。
let motionManager = CMMotionManager()
if motionManager.isAccelerometerAvailable{
let queue = OperationQueue()
motionManager.startAccelerometerUpdates(to: queue, withHandler:
{data, error in
guard let data = data else{
return
}
print("X = \(data.acceleration.x)")
print("Y = \(data.acceleration.y)")
print("Z = \(data.acceleration.z)")
}
)
} else {
print("Accelerometer is not available")
}
别忘了导入CoreMotion!
更新了解决方案 如果设备以超过10 km / h的速度移动,这是一个如何获取加速度计数据的工作示例。
import UIKit
import CoreMotion
import CoreLocation
class ViewController: UIViewController {
var timer = Timer()
var locationManager = CLLocationManager()
let motionManager = CMMotionManager()
override func viewDidLoad() {
super.viewDidLoad()
scheduledTimerWithTimeInterval() //Calling function with timer
// Do any additional setup after loading the view, typically from a nib.
}
func scheduledTimerWithTimeInterval(){
// Scheduling timer to Call the function **getSpeed** with the interval of 1 seconds
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.getSpeed), userInfo: nil, repeats: true)
}
func getSpeed(){
var speed: CLLocationSpeed = CLLocationSpeed()
speed = Double((locationManager.location?.speed)!)
print(String(format: "%.0f km/h", speed * 3.6)) //Current speed in km/h
//If speed is over 10 km/h
if(speed * 3.6 > 10 ){
//Getting the accelerometer data
if motionManager.isAccelerometerAvailable{
let queue = OperationQueue()
motionManager.startAccelerometerUpdates(to: queue, withHandler:
{data, error in
guard let data = data else{
return
}
print("X = \(data.acceleration.x)")
print("Y = \(data.acceleration.y)")
print("Z = \(data.acceleration.z)")
}
)
} else {
print("Accelerometer is not available")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 1 :(得分:1)
我正在尝试创建一个应用程序(在swift中),它将检测iPhone是否处于运动状态。
这可能是不可能的。让我们说iPhone正以3公里/小时的速度向一个方向稳步前进。 Core Motion无法检测到这一点,因为它不是加速度!所以你唯一的希望就是使用核心位置;这将为您提供基于GPS的航向和速度,但当然精度会有所限制。