iOS 9 [locationManager.requestWhenInUseAuthorization()]警报视图在出现后很快消失

时间:2015-10-05 17:51:35

标签: ios swift mapkit core-location

我配置了一个非常基本的应用程序。它使用导航控制器,以及我已配置为我的地图视图控制器的视图控制器。

当应用程序启动时,它会启动到Root View Controller,从那里,我有一个按钮,它被配置为segue到地图视图控制器并显示地图。发生这种情况时,将显示警报视图,但在我可以选择允许/不允许之前,它会消失并加载地图。

为什么警报视图会自行消失?

我已相应地配置了info.plist文件,添加了必要的框架并添加了相应的委托。

以下是我配置的代码:

import UIKit
import MapKit
import CoreLocation


class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

@IBOutlet weak var map: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation = locations[0]

    let latitude = userLocation.coordinate.latitude
    let longitude = userLocation.coordinate.longitude
    let latDelta: CLLocationDegrees = 0.01
    let lonDelta: CLLocationDegrees = 0.01
    let coordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    let span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
    let region: MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
    map.setRegion(region, animated: true)
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print(error)
}

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


}

任何帮助将不胜感激!提前谢谢!

2 个答案:

答案 0 :(得分:4)

在viewDidLoad之外声明您的locationManager ivar。它在viewDidLoad完成后被释放,因为没有任何强引用。您可能也应该在用户授予访问权限后才开始扫描。

var locationManager:CLLocationManager!

override func viewDidLoad() {
  super.viewDidLoad()

  locationManager = CLLocationManager()
  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBest
  let authorizationStatus = CLLocationManager.authorizationStatus()
    if (authorizationStatus == CLAuthorizationStatus.NotDetermined) {
      locationManager.requestWhenInUseAuthorization()
    } else if (authorizationStatus == CLAuthorizationStatus.AuthorizedWhenInUse) {
      locationManager.startUpdatingLocation()
    }
}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
  if (status == CLAuthorizationStatus.AuthorizedWhenInUse) {
    locationManager.startUpdatingLocation()
  }

}

答案 1 :(得分:0)

因为你做错了。 CLLocationManagerDelegate协议有一个名为didChangeAuthorizationStatus的方法。如果用户允许或不允许应用使用位置,您应该检查那里。检查完之后,您应该调用startUpdatingLocation。请务必使用主队列上的dispatch_async执行此代码所需的所有UI更新。