没有互联网时位置管理器崩溃

时间:2015-01-27 23:54:10

标签: objective-c swift

当用户连接到互联网时,程序运行正常。但是,当用户未连接时,应用程序崩溃:

Error:The operation couldn’t be completed. (kCLErrorDomain error 8.)
fatal error: unexpectedly found nil while unwrapping an Optional value

我喜欢在崩溃并显示警报控件之前捕获错误

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        if (error != nil) {
            println("Error:" + error.localizedDescription)
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.displayLocationInfo(pm)
            currentLoc = manager.location
            currentLocGeoPoint = PFGeoPoint(location:currentLoc)
            var query = PFQuery(className:"Restaurant") //default: Restaurant
            query.whereKey("RestaurantLoc", nearGeoPoint:currentLocGeoPoint, withinMiles:setDistanceMiles) //filter by miles
            query.limit = 1000 //limit number of results
            query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]!, error: NSError!) -> Void in
                if objects.isEmpty {
                    //NO RESULTS
                    let alertController = UIAlertController(title: "Unavailable Area", message:
                        "This app is not available in your area yet. We'll try our best to have it up and running as soon as possible.", preferredStyle: UIAlertControllerStyle.Alert)
                    alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
                    self.presentViewController(alertController, animated: true, completion: nil)
                    self.navigationController!.popViewControllerAnimated(true)
                } else {
                    newArray = objects
                }
                self.hideActivityIndicator(self.view)
            }
        } else {
            println("error: \(error)")
        }
    })
}

enter image description here

2 个答案:

答案 0 :(得分:2)

问题在于您的if声明。你这么说:

if (error != nil) {
    println("Error:" + error.localizedDescription)
}
if placemarks.count > 0 { // ...

嗯,错误。你被告知有错误。但是你没有听!你没有停止!你只是继续,好像什么都没发生,并尝试访问placemarks变量 - 没有返回。您需要在此处使用逻辑,以便在出现错误时退出

if (error != nil) {
    println("Error:" + error.localizedDescription)
    return // go no further!
}
if placemarks.count > 0 { // ...

但请注意,最好首先检查placemarks nil

if placemarks == nil {
    // check error
    // return
}
if placemarks.count > 0 { // ...

答案 1 :(得分:1)

我认为你需要实现locationManager:didFailWithError,告诉代表何时无法检索位置。然后,您只需要通过适当的响应来处理错误。

供参考:CLLocationManagerDelegate apple docs