Airport tutorial app unstable

I have the app working abut after a while it usually crashes with error "Fatal error: Index out of range"
Any ideas on how to make it more stable?

AppDelegate code

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, ESTBeaconManagerDelegate{

    var window: UIWindow?

    let beaconManager = ESTBeaconManager()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        self.beaconManager.delegate = self
        self.beaconManager.requestAlwaysAuthorization()
        
        self.beaconManager.startMonitoringForRegion(CLBeaconRegion(
            proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!,
            major: 60556, minor: 28595, identifier: "monitored region"))
        
        UIApplication.sharedApplication().registerUserNotificationSettings(
            UIUserNotificationSettings(forTypes: .Alert, categories: nil))
        
        return true
    }

    func beaconManager(manager: AnyObject, didEnterRegion region: CLBeaconRegion) {
        let notification = UILocalNotification()
        notification.alertBody =
            "Your gate closes in 47 minutes. " +
            "Current security wait time is 15 minutes, " +
            "and it's a 5 minute walk from security to the gate. " +
        "Looks like you've got plenty of time!"
        UIApplication.sharedApplication().presentLocalNotificationNow(notification)
    }
    
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

ViewController code

import UIKit

class ViewController: UIViewController, ESTBeaconManagerDelegate{
   
    @IBOutlet weak var closest: UILabel!
   
    @IBOutlet weak var secondClosest: UILabel!
    @IBOutlet weak var furthestAway: UILabel!
    
    let placesByBeacons = [
        "60556:28595": [
            "Heavenly Sandwiches (Key-Blueberry)": 50, // read as: it's 50 meters from
            // "Heavenly Sandwiches" to the beacon with
            // major 60556 and minor 28595
            "Green & Green Salads": 150,
            "Mini Panini": 325
        ],
        "46616:23244": [
            "Heavenly Sandwiches (Ice)": 250,
            "Green & Green Salads": 100,
            "Mini Panini": 20
        ],
        "8191:22360": [
            "Heavenly Sandwiches (Mint)": 350,
            "Green & Green Salads": 100,
            "Mini Panini": 170
        ]
    ]
   
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.beaconManager.startRangingBeaconsInRegion(self.beaconRegion)
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        self.beaconManager.stopRangingBeaconsInRegion(self.beaconRegion)
    }
    
    let beaconManager = ESTBeaconManager()
    let beaconRegion = CLBeaconRegion(
        proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")!,
        identifier: "ranged region")

    override func viewDidLoad() {
        super.viewDidLoad()
        self.beaconManager.delegate = self
        self.beaconManager.requestAlwaysAuthorization()
        
        // Do any additional setup after loading the view, typically from a nib.
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func placesNearBeacon(beacon: CLBeacon) -> [String] {
        let beaconKey = "\(beacon.major):\(beacon.minor)"
                if let places = self.placesByBeacons[beaconKey] {
            let sortedPlaces = Array(places).sort() { $0.1 < $1.1 }.map { $0.0 }
            return sortedPlaces
        }
        return []
    
        }
    
    func beaconManager(manager: AnyObject, didRangeBeacons beacons: [CLBeacon],
        inRegion region: CLBeaconRegion) {
            if let nearestBeacon = beacons.first {
                let places = placesNearBeacon(nearestBeacon)
                // TODO: update the UI here
                print(places) // TODO: remove after implementing the UI
            
                closest.text? = places[0]
                secondClosest.text? = places[1]
                furthestAway.text? = places[2]
            }
    }

}

Can you post the stack trace or screenshot of the error? Trying to establish which line exactly causes the problem.

image

image

Aha! Thank you!

Looks like changing this:

func placesNearBeacon(beacon: CLBeacon) -> [String] {
    let beaconKey = "\(beacon.major):\(beacon.minor)"
    if let places = self.placesByBeacons[beaconKey] {
        let sortedPlaces = Array(places).sort() { $0.1 < $1.1 }.map { $0.0 }
        return sortedPlaces
    }
    return []
}

func beaconManager(manager: AnyObject, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
    if let nearestBeacon = beacons.first {
        let places = placesNearBeacon(nearestBeacon)
        // TODO: update the UI here
        print(places) // TODO: remove after implementing the UI
    
        closest.text? = places[0]
        secondClosest.text? = places[1]
        furthestAway.text? = places[2]
    }
}

to this:

func placesNearBeacon(beacon: CLBeacon) -> [String]? {
    let beaconKey = "\(beacon.major):\(beacon.minor)"
    if let places = self.placesByBeacons[beaconKey] {
        let sortedPlaces = Array(places).sort() { $0.1 < $1.1 }.map { $0.0 }
        return sortedPlaces
    }
    return nil
}

func beaconManager(manager: AnyObject, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
    if let nearestBeacon = beacons.first, places = placesNearBeacon(nearestBeacon) {
        // TODO: update the UI here
        print(places) // TODO: remove after implementing the UI
    
        closest.text? = places[0]
        secondClosest.text? = places[1]
        furthestAway.text? = places[2]
    }
}

… should prevent the crashes.

Thank you
Working like a dream now

Brian

1 Like