代码之家  ›  专栏  ›  技术社区  ›  CFRJ

当用户允许位置跟踪时更新位置

  •  0
  • CFRJ  · 技术社区  · 9 年前

    我试着模拟用户接受位置跟踪时的位置。当他们已经接受位置跟踪并加载视图时,代码可以工作,但我希望在他们按位置跟踪时重新加载视图。

    override func viewDidLoad() {
        super.viewDidLoad()
    
    
        //Prepare to get User
         if CLLocationManager.authorizationStatus() != .authorizedAlways {
             // May need to change to support location based notifications
            locationManager.requestAlwaysAuthorization()
            print("hello")
    
            mapView.setVisibleMapRect(mapView.visibleMapRect, animated: true)
         }else {
            locationManager.startUpdatingLocation()
         }
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        mapView.delegate = self
    
    }
    

    动画到用户位置代码

    //Get user location
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //Show the map at the users current location
        let location = locations[0]
        let span:MKCoordinateSpan = MKCoordinateSpanMake(0.02,0.02 )
        let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
        mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = true
    
        locationManager.stopUpdatingLocation()
    
    
     }
    
    2 回复  |  直到 9 年前
        1
  •  2
  •   Vasil Hristov    9 年前

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            locationManager.requestAlwaysAuthorization()
            break
        case .authorizedWhenInUse:
            locationManager.startUpdatingLocation()
            break
        case .authorizedAlways:
            locationManager.startUpdatingLocation()
            break
        default:
            break
        }
    }
    
        2
  •  0
  •   Dávid Pásztor    9 年前

    用于更新中位置的所有方法 CLLocationManager 是异步的,因此无论代码的实现如何,用户都可能会延迟允许位置访问实际发生的位置更新。

    然而,通过呼叫 CLLocationManager().requestLocation() 在…内 locationManager(didChangeAuthorizationStatus)

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            locationManager.requestAlwaysAuthorization()
        case .authorizedWhenInUse:
            locationManager.requestLocation()
        case .authorizedAlways:
            locationManager.requestLocation()
        default:
            break
        }
    }
    

    这将自动调用您的 CLLocationManagerDelegate 方法 requestLocation