ios - applicationWillEnterForeground 使我的应用程序崩溃后更改 IBOutlets 值

标签 ios xcode swift reachability iboutlet

使用:XCode 7、iPhone 5 (iOS 8.3)、WiFi、可达性(检查互联网连接)。 当我的应用程序处于后台并且我单击打开我的应用程序时,它会检查连接并加载一些函数,并且在我尝试签名的函数之一中:

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

错误: fatal error :在解包可选值时意外发现 nil

仅当我的应用程序通过主视图 Controller 的功能更改 applicationWillEnterForeground 中的 IBOutlet 值时才会发生这种情况 self.viewController.functionName()

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

checkConn() 检查连接的可达性并更改 IBOutlets 值,例如 .image 和 .text

有什么办法可以解决吗?

最佳答案

经过大量测试,我发现这个方法效果很好:

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()
    }
}

关于ios - applicationWillEnterForeground 使我的应用程序崩溃后更改 IBOutlets 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31271095/

相关文章:

ios - 在循环中使用 dataWithContentsOfURL 内存泄漏

ios - 织物/Crashlytics : 'ANSCompatibility.h' file not found

ios - 过滤 View 在点击时会导致详细 View 不正确,但在滑动时会导致详细 View 正确

Xcode 6 界面生成器,无法将 Storyboard窗口链接到代码

swift - dispatch_async 与 dispatch_sync 在获取数据中的对比。 swift

ios - 为什么BackgroundTasks中的异步/长时间运行操作不起作用?

ios - SQL 错误 : Not an Error

ios - 带有背景图像的 UIButton 突出显示状态错误

c# - MongoDB 不查询

iphone - 在 xCode 上发布 iPhone 应用程序 (Windows)