解雇视图控制器

时间:2016-08-28 19:20:14

标签: ios viewcontroller swift3

我有一个简单的ViewController,可以显示我当前的位置坐标。

一切正常,但是当我关闭ViewController时,应用程序崩溃时没有任何特定的错误日志。

类代码如下:

import UIKit

class LocationViewController:   UIViewController, CLLocationManagerDelegate, MKMapViewDelegate, UIPopoverPresentationControllerDelegate {



// General objects
@IBOutlet var closeButton: UIButton!
@IBOutlet var latitudeLabel: UILabel!
@IBOutlet var longitudeLabel: UILabel!
@IBOutlet var infoButton: UIButton!


// Global variables
var location: CLLocationManager? = CLLocationManager()
var geocoder = CLGeocoder();
var placemark = CLPlacemark();
var hasPin: Bool = false;

override func viewDidLoad() {
    super.viewDidLoad()

    // Ask for Authorisation from the User.
    location?.requestAlwaysAuthorization();

    // For use in foreground
    location?.requestWhenInUseAuthorization();

    getCurrentLocation();
}

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



@IBAction func closeButton(_ sender: AnyObject) {
    self.dismiss(animated: true, completion: {
        print("dismissing locationViewController");
        self.location = nil;
    });
}



@IBAction func infoButton(_ sender: AnyObject) {
    // TODO
}


// MARK: - General functions
func getCurrentLocation() -> Void {
    if (CLLocationManager.locationServicesEnabled()) {
        location?.delegate = self;
        location?.desiredAccuracy = kCLLocationAccuracyBest;
        location?.startUpdatingLocation();
    }
}





// MARK: - CLLocationManagerDelegate

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("ERROR = \(error)");
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    // Gets the user coordinates
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate;
    USER_LATITUDE = locValue.latitude;
    USER_LONGITUDE = locValue.longitude;

    longitudeLabel.text = "\(USER_LONGITUDE)";
    latitudeLabel.text = "\(USER_LATITUDE)";

    location?.stopUpdatingLocation()
}

有没有人知道为什么会这样?

没有提示错误日志,这让我更加困惑。

首先,我认为我必须将location变量设置为可选,然后在我解除VC但仍然发生崩溃时将其设置为nil。

Crashlytics说应用程序在LocationViewController第0行崩溃,这实际上很奇怪。

我通过按钮点击另一个VC来调用此ViewController,如下所示:

@IBAction func locationButton(_ sender: AnyObject) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil);
    let viewController = storyboard.instantiateViewController(withIdentifier: "locationVC");
    self.present(viewController, animated: true, completion: nil);
}

我在iOS 10上使用Swift3和最新的Xcode Beta版本。

  • 感谢

2 个答案:

答案 0 :(得分:1)

替换它:

var location: CLLocationManager? = CLLocationManager()

有了这个:

let location = CLLocationManager()

根据需要更改所有代码(这不再是可选项,因此无需解包)并删除尝试将其设置为nil的行。

如果您担心位置管理员可能会在您解雇时尝试获取您的位置,请执行viewWillDisappear并告知其停止更新。

答案 1 :(得分:0)

您需要在Info.plist中添加隐私条目,并请求授权以使用位置服务。可以在此处找到一个很好的概述:http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/