2015-01-05 2 views
2

프로그래밍 과목을 위해 내 학교 프로젝트를하고 있습니다. 스위프트의 Xcode에서 일하고 있습니다. 자이로 스코프를 사용하는 응용 프로그램을 만들고 싶습니다. 모르겠지만 어떻게 든 내 아이폰에서 실행되지 않을 것입니다. Xcode에서 수정 방법을 모르는 것입니다. 프로그램을 실행하면 "치명적인 오류가 발생합니다 : 예기치 않게 선택 값을 언 래핑하는 동안 발견되었습니다. (lldb) " 자이로 스코프를 사용하여 아이폰 화면에서 회전 각도 (요, 피치, 롤)를도 단위로 표시합니다. 누군가 제가이 일을 도와 주시면 정말 감사 할 것입니다. 미리 감사드립니다.스위프트 자이로 스코프 yaw, pitch, roll

내의 ViewController 코드 : 암시 적으로 풀어 선택적 항목으로 작업하는이 두 라인에서

import UIKit 
import CoreMotion 

class ViewController: UIViewController { 

    var currentMaxRotX: Double = 0.0 
    var currentMaxRotY: Double = 0.0 
    var currentMaxRotZ: Double = 0.0 

    let motionManager = CMMotionManager() 

    @IBOutlet var rotX : UILabel! = nil 
    @IBOutlet var rotY : UILabel! = nil 
    @IBOutlet var rotZ : UILabel! = nil 

    @IBOutlet var maxRotX : UILabel! = nil 
    @IBOutlet var maxRotY : UILabel! = nil 
    @IBOutlet var maxRotZ : UILabel! = nil 


    @IBOutlet weak var RollLabel: UILabel! = nil 

    @IBOutlet weak var PitchLabel: UILabel! = nil 

    @IBOutlet weak var YawLabel: UILabel! = nil 

    override func viewDidLoad() { 

     if motionManager.gyroAvailable { 

      if !motionManager.gyroActive { 
       motionManager.gyroUpdateInterval = 0.2 
       motionManager.startGyroUpdates() 
       //motionManager = [[CMMotionManager alloc]init]; should I use this ??? 
       //motionManager.deviceMotionUpdateInterval = 0.2; 
       //motionManager.startDeviceMotionUpdates() 

       motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(gyroData: CMGyroData!, error: NSError!)in 
        self.outputRotationData(gyroData.rotationRate) 
        if (error != nil) 
        { 
         println("\(error)") 
        } 
       })  
      } 
     } else { 
       var alert = UIAlertController(title: "No gyro", message: "Get a Gyro", preferredStyle: UIAlertControllerStyle.Alert) 
       alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) 
       self.presentViewController(alert, animated: true, completion: nil) 
    } 


    super.viewDidLoad() 
    } 

    // radians to degrees 
    func radians(fromDegrees degrees: Double) -> Double { 
     return 180 * degrees/M_PI 
    } 

    func outputRotationData(rotation:CMRotationRate) 
    { 
     rotX.text = NSString(format:"Rotation X: %.4f",rotation.x) 
     if fabs(rotation.x) > fabs(currentMaxRotX) 
     { 
      currentMaxRotX = rotation.x 
     } 

     rotY.text = NSString(format:"Rotation Y: %.4f", rotation.y) 
     if fabs(rotation.y) > fabs(currentMaxRotY) 
     { 
      currentMaxRotY = rotation.y 
     } 
     rotZ.text = NSString(format:"Rotation Z:%.4f", rotation.z) 
     if fabs(rotation.z) > fabs(currentMaxRotZ) 
     { 
      currentMaxRotZ = rotation.z 
     } 

     maxRotX.text = NSString(format:"Max rotation X: %.4f", currentMaxRotX) 
     maxRotY.text = NSString(format:"Max rotation Y:%.4f", currentMaxRotY) 
     maxRotZ.text = NSString(format:"Max rotation Z:%.4f", currentMaxRotZ) 

     var attitude = CMAttitude() 
     var motion = CMDeviceMotion() 
     motion = motionManager.deviceMotion 
     attitude = motion.attitude 


     YawLabel.text = NSString (format: "Yaw: %.2f", attitude.yaw) //radians to degress NOT WORKING 
     PitchLabel.text = NSString (format: "Pitch: %.2f", attitude.pitch)//radians to degress NOT WORKING 
     RollLabel.text = NSString (format: "Roll: %.2f", attitude.roll)//radians to degress NOT WORKING 
     } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 
+0

이 게시물은 http://stackoverflow.com/questions/24643522/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-values ​​ –

+0

당신이 더 구체적 일 수 있습니다 필요한 모든해야한다, 왜냐하면 나는 초보자이기 때문이다. 정확히 어디서 오류인지 또는 내 코드에서 어떤 오류가 있는지 알 수 없습니다. 고맙습니다. – Moonwalker4z

답변

9

: 당신이 ? 또는 !없이 사용할 수 있지만 그들은 nil이라면 그들은 당신의 프로그램을 충돌합니다 . 이 경우 액세스하기 전에 motionManager.startDeviceMotionUpdates()을 호출하지 않았으므로 motionManager.deviceMotionnil입니다.

귀하의 viewDidLoad 방법은이 작업을 수행 할 수있는 권리 장소 :

override func viewDidLoad() { 

    if motionManager.gyroAvailable { 
     motionManager.deviceMotionUpdateInterval = 0.2; 
     motionManager.startDeviceMotionUpdates() 

     motionManager.gyroUpdateInterval = 0.2 
     motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue()) { 
      [weak self] (gyroData: CMGyroData!, error: NSError!) in 

      self?.outputRotationData(gyroData.rotationRate) 
      if error != nil { 
       println("\(error)") 
      } 
     } 
    } else { 
     // alert message 
    } 

    super.viewDidLoad() 
} 

이 몇 가지 추가 변경이 있습니다

  1. 당신은 startGyroUpdatesToQueue() 전에 startGyroUpdates()를 호출 할 필요는 없습니다가.
  2. 스위프트는이 같은 완성 핸들러에 대해 trailing closures을 사용하여 쓰기 및 읽기가 더 편리합니다.
  3. 참조주기를 피하려면 self을 완료 핸들러 내에 weak으로 선언하십시오. 그러면 self에 액세스 할 때 선택적 체인을 사용해야합니다.
관련 문제