2016-12-22 10 views

答えて

2

あなたは、加速度計からデータを取得するになっているはずです。ここで

は、あなたが情報を取得できる方法の一例です。

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キロ以上/時間で移動する場合、加速度計データを取得する方法の実施例です。

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. 
} 
} 
+0

デバイスが特定の速度で動いている場合にのみ、このコードを実行できるようにするにはどうすればよいですか? – appsarecool1

+1

新しい例を見てください。あなたのView.Controllerにコードをコピーするだけです。あなたの質問に答えられていると感じたら、答えとしてマークすることを忘れないでください。 – Englund0110

1

私はiPhoneが動いているかどうかを検出します(SWIFT)でアプリを作成しようとしています。できない場合があります

。 iPhoneが3km/hrで一方向に着実に動いているとしましょう。コア・モーションはアクセラレーションではないため、これを検出できません!ですから、あなたの唯一の希望はコアロケーションを使用することです。それはもちろん、精度は多少制限されるでしょうが、あなたは、GPSに基づく見出しとスピード与えます。

関連する問題