为了在手表模拟器中进行位置检测,您还需要设置 iPhone 模拟器的位置。我建议您按照以下步骤操作
- 在 iPhone 模拟器中设置位置,(调试 -> 位置 -> 自定义位置)
- 在手表模拟器中设置位置,(调试->位置->自定义位置)
- 有时,当您运行 watchkit 应用程序时,iPhone 模拟器中的位置会重置为无。因此,在您访问该位置之前,在手表扩展代码中放置断点。在两个模拟器中都设置了检查位置。
希望这可以帮助。
快速示例代码,
class LocationManager: NSObject, CLLocationManagerDelegate
{
static let sharedInstance = VCLocationManager()
private var locationManager : CLLocationManager?
private override init()
{
}
func initLocationMonitoring()
{
//didChangeAuthorizationStatus is called as soon as CLLocationManager instance is created.
//Thus dont check authorization status here because it will be always handled.
if locationManager == nil
{
locationManager = CLLocationManager()
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.delegate = self
}
else
{
getCurrentLocation()
}
}
func getCurrentLocation()
{
let authorizationStatus = CLLocationManager.authorizationStatus()
handleLocationServicesAuthorizationStatus(authorizationStatus)
}
func handleLocationServicesAuthorizationStatus(status: CLAuthorizationStatus)
{
switch status
{
case .NotDetermined:
handleLocationServicesStateNotDetermined()
case .Restricted, .Denied:
handleLocationServicesStateUnavailable()
case .AuthorizedAlways, .AuthorizedWhenInUse:
handleLocationServicesStateAvailable()
}
}
func handleLocationServicesStateNotDetermined()
{
locationManager?.requestWhenInUseAuthorization()
}
func handleLocationServicesStateUnavailable()
{
//Ask user to change the settings through a pop up.
}
func handleLocationServicesStateAvailable()
{
locationManager?.requestLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
handleLocationServicesAuthorizationStatus(status)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
guard let mostRecentLocation = locations.last else { return }
print(mostRecentLocation)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("CL failed: \(error)")
}
}