应用程序崩溃是因为launchOptions在发布时为零

时间:2016-03-28 11:57:41

标签: ios swift

这是我在swift 2.2中的代码,我写的是

didfinishLaunchingWithOptions

作为

if let locationValue : AnyObject? = launchOptions![UIApplicationLaunchOptionsLocationKey] as? [NSObject : AnyObject] {
    if (locationValue != nil) {
        let app : UIApplication = UIApplication.sharedApplication()
        var bgTask : UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
        bgTask = app.beginBackgroundTaskWithExpirationHandler({ () -> Void in
            app.endBackgroundTask(bgTask)
        })
        self.startLocationUpdates()
        }}

此行发生错误(EXC_BAD_INSTRUCTION)

 if let locationValue : AnyObject? = launchOptions![UIApplicationLaunchOptionsLocationKey] as? [NSObject : AnyObject] {

任何人都可以帮我解决如何处理零案件吗?我也尝试过.let声明..提前谢谢你。

1 个答案:

答案 0 :(得分:5)

您在应用程序中使用感叹号的任何地方都是您的应用可能会崩溃的地方。在大多数情况下,您通常可以解决它是用问号替换感叹号。

didFinishLaunchingWithOptions的签名是这样的:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool

此处的相关参数为launchOptions,其类型为[NSObject: AnyObject]?,是一个可选字典。在我们可以调用它的方法之前(包括尝试通过下标操作符访问元素),我们必须解开它。

在您的情况下,最简单的解决方案是:

if let locationValue = launchOptions?[UIApplicationLaunchOptionsLocationKey] {
    // use the location value
}

the official Apple documentation

  
      
  • UIApplicationLaunchOptionsLocationKey
  •   
     

此密钥的存在表示该应用已启动   响应传入的位置事件。这个键的值是   NSNumber对象包含布尔值。你应该使用   存在此键作为创建CLLocationManager对象的信号   并再次启动位置服务。位置数据仅发送至   位置管理员委托而不使用此密钥。

在上面的代码段中,由于字典的类型,locationValue的类型为AnyObject(非可选)。但根据文档,我们知道它将是NSNumber代表Bool(在Swift中可以自由地桥接到有用的类型)。

我们可能只关心值为真的情况,对吧?

因此,我们可以将代码段重写为以下内容:

if let locationValue = launchOptions?[UIApplicationLaunchOptionsLocationKey] as? Bool where locationValue {
    // the app was launched in response to a location event
    // do your location stuff
}

严格地说,根据文件:

  

此密钥的存在表示应用程序是为响应传入的位置事件而启动的。

在这个措辞和实际值只是一个真/假值这一事实之间,我几乎打赌,单独存在密钥这一事实足以让假设价值为true。如果未针对位置事件启动应用程序,则该密钥可能根本不存在。如果是,则该值可能始终为true

如果你想打赌这个假设,你可以简单地使用_作为变量名,因为我们不会使用它:

if let _ = launchOptions?[UIApplicationLaunchOptionsLocationKey] {
    // etc...
}
相关问题