ios - 如果位置关闭,swift 2 会阻止程序运行

标签 ios swift

我想检查并查看该位置是否已打开,如果未打开或用户未授予使用位置的权限,应用程序将退出(不会运行)。 有没有办法做到这一点,因为人们说不建议使用 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/

相关文章:

ios - 在 Swift 中自动播放音频文件

iphone - 如何删除工具栏上 UIBarButtonItems 之间的默认可用空间?

ios - Spritekit 在 SKSpriteNode 子类中获取 Sprite 场景的最佳方法

swift - 为什么是 CFloat 和 CDouble? func addNewValue(newVal : CFloat, atTime time: CDouble) -> CFloat {}

ios - 如何使用返回 UIBezierPath 的函数来启动动画?

多次传递 CVarArg 的 swift 3 问题

ios - CosmicMind/Material - 如何在 NavigationDrawerController 中调用 pushViewController?

ios - TableView 的 UISearchController

swift - 以编程方式约束按钮

ios - 当我尝试实例化 UINib 时,我得到 : this class is not key value coding-compliant for the key view