2016-07-09 39 views
0

我想检查该位置是否处于打开状态,如果该位置未打开,或者用户未授予使用位置的权限,则应退出(不会运行)。 有没有办法做到这一点,因为人们都说不推荐使用exit(0),这会让苹果难过。 :Dswift 2如果位置关闭,则阻止程序的运行

+1

[退出iPhone应用程序的正确方法](http://stackoverflow.com/q/355168/335858) – dasblinkenlight

回答

2

您可以在屏幕上放置一个视图(全宽和高度),并带有一个标签,告诉用户只有在启用位置服务的情况下才能使用该应用。当然用户不应该以任何方式与这个视图进行交互。

这里有一个例子辅助类:

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()推出了应用程序之后和类应处理剩下的...

1

苹果不喜欢exit(0)的一个原因。我强烈建议您不要自行终止应用程序。也许你可以让用户使用功能有限的应用程序?另一种选择是在没有任何行动的情况下做出警戒,或者做出什么都不做的行动。

相关问题