2016-12-10 35 views
0

任何人都可以提供一段簡短的代碼片段,讓我知道iPhone的磁性標題嗎? 我不想要Objective-C。我在Swift中需要它。適用於iOS的磁性標題示例代碼

到目前爲止我寫這幾行,但它不返回我任何值:

let locManager = CLLocationManager() 
locManager.desiredAccuracy = kCLLocationAccuracyBest 
locManager.requestWhenInUseAuthorization() 
locManager.startUpdatingLocation() 

locManager.startUpdatingHeading() 
locManager.headingOrientation = .portrait 
locManager.headingFilter = kCLHeadingFilterNone 

print(locManager.heading?.trueHeading.binade as Any) 

謝謝!

+0

你應該問你的問題!不要求別人寫你的代碼。也許你應該找一個自由職業者! –

回答

1

您沒有設置位置管理器的委託。 iOS不會立即更新您的位置。相反,它會調用你的代理提供的功能,當它有一個位置/標題更新。這種設置背後的原因是效率。這10個位置管理器將會要求在GPS更新時收到通知,而不是10個具有10個不同位置管理器的應用在GPS硬件上競爭時間。

試試這個:

class ViewController: UIViewController, CLLocationManagerDelegate { 
    @IBOutlet weak var label: UILabel! 
    var locManager = CLLocationManager() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locManager.desiredAccuracy = kCLLocationAccuracyBest 
     locManager.requestWhenInUseAuthorization() 
     locManager.headingOrientation = .portrait 
     locManager.headingFilter = kCLHeadingFilterNone 
     locManager.delegate = self // you forgot to set the delegate 

     locManager.startUpdatingLocation() 
     locManager.startUpdatingHeading() 
    } 

    // MARK: - 
    // MARK: CLLocationManagerDelegate 
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 
     print("Location Manager failed: \(error)") 
    } 

    // Heading readings tend to be widely inaccurate until the system has calibrated itself 
    // Return true here allows iOS to show a calibration view when iOS wants to improve itself 
    func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool { 
     return true 
    } 

    // This function will be called whenever your heading is updated. Since you asked for best 
    // accuracy, this function will be called a lot of times. Better make it very efficient 
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { 
     label.text = "\(newHeading.magneticHeading)" 
    } 
} 
+0

非常感謝您的幫助。我花了幾個小時。 – jimmy2times

+0

現在我有一個問題,當標題可用時,應用程序如何知道這3個函數中的哪一個要調用? – jimmy2times