我想检查并查看该位置是否已打开,如果未打开或用户未授予使用位置的权限,应用程序将退出(不会运行)。 有没有办法做到这一点,因为人们说不建议使用 exit(0) 并且会让苹果伤心。 :D
最佳答案
您可以在屏幕上放置一个 View (全宽和全高),并带有一个标签,告诉用户只能在启用位置服务的情况下使用该应用程序。当然,用户不应该以任何方式与这个 View 进行交互。
这里是一个辅助类的例子:
import UIKit
import CoreLocation
class LocationHelper: NSObject, CLLocationManagerDelegate {
private static let sharedInstance = LocationHelper()
private var locationManager: CLLocationManager! {
didSet {
locationManager.delegate = self
}
}
private override init() {}
class func setup() {
sharedInstance.locationManager = CLLocationManager()
}
private func informUserToEnableLocationServices() {
let infoPopup = UIAlertController(title: "Location Services", message: "Sorry, but you have to enable location services to use the app...", preferredStyle: .Alert)
let tryAgainAction = UIAlertAction(title: "Try again", style: .Default) { (action) in
if CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse {
self.informUserToEnableLocationServices()
}
}
infoPopup.addAction(tryAgainAction)
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
let rootViewController = appDelegate?.window?.rootViewController
rootViewController?.presentViewController(infoPopup, animated: true, completion: nil)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .NotDetermined:
locationManager.requestWhenInUseAuthorization()
case .AuthorizedWhenInUse:
break
default:
informUserToEnableLocationServices()
}
}
}
在应用程序启动后简单地调用 LocationHelper.setup()
类应该处理其余的...
关于ios - 如果位置关闭,swift 2 会阻止程序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279564/