Search code examples
iosxcodeswiftreachabilityiboutlet

Change IBOutlets values after applicationWillEnterForeground crashes my app


Using: XCode 7, iPhone 5 (iOS 8.3), WiFi, Reachability (check the internet connection). While my app is in background and I click to open my app it checks the conncetion and load some functions and in 1 of the functions I try to sign:

imageView.image = UIImage(named: "imagename")

error: fatal error: unexpectedly found nil while unwrapping an Optional value

This happens only when my app change an IBOutlet value in applicationWillEnterForeground with function to primary view controller self.viewController.functionName()

class AppDelegate: UIResponder, UIApplicationDelegate {
     var viewController:ViewController = ViewController()
     func applicationWillEnterForeground(application: UIApplication) {
        self.viewController.checkConn()
    }
}

checkConn() check the connection with Reachability and change IBOutlets values like .image and .text

Is there any way to fix it?


Solution

  • After a lot of tests I found this method which works great:

    class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        var viewController:ViewController?
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
            viewController = self.window!.rootViewController as? ViewController
            return true
        }
        func applicationWillEnterForeground(application: UIApplication) {
            viewController!.checkConn()
        }
    }