简体   繁体   中英

iPhone App crashes when receiving push notification

I have an app that sends me the location of the device when I send a push notification. But, while the app is running in the foreground the app crashes on receiving the push notification.

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler:(UIBackgroundFetchResult) -> Void ) 
{
    NSLog("\(userInfo)")
    if (managedConfig["locationTrackingDisabled"] ?? false) as! Bool == false {
    locationManager.startUpdatingLocation()
    }
    let seconds = 4.0
    let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per seconds
    let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

    dispatch_after(dispatchTime, dispatch_get_main_queue(), {
        completionHandler(UIBackgroundFetchResult.NewData)
    })
}

There's not really enough information here to figure out what is going wrong, but if I put on my psychic debugging hat, the if statement here can easily crash due to force casting to a Bool if:

  1. managedConfig is an NSDictionary
  2. it has a locationTrackingDisabled key which stores something other than a Bool (perhaps an NSString )

A better way of checking is to use an if let statement to safely determine if the value in the dictionary has the expected type.

if let trackLocation = managedConfig["locationTrackingDisabled"] as? Bool, trackLocation {
    locationmanager.startUpdatingLocation()
}

Note that you can run your app on a device through Xcode and still receive push notifications. Also, if you're going to distribute an app through the Store, it's highly recommended that you have some way of tracking crashes, ie via HockeyApp, Crashlytics, Crittercism, etc. There are lots of options out there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM