我想像这样从第一个视图重新启动应用程序:
func applicationWillEnterForeground(_ application: UIApplication) {
let storyBoard: UIStoryboard = UIStoryboard(name: "SplashScreen", bundle: nil)
let splashScreen = storyBoard.instantiateViewController(withIdentifier: "splashVC") as! SplashScreenController
self.window?.addSubview(splashScreen.view)
}
但是当应用再次被唤醒时。我的代表返回零。为什么?
SplashScreenVM.swift:
import Foundation
protocol SplashScreenVMProtocol: class {
func fetchDataSuccessfuly()
func failedFetchData()
}
class SplashScreenVM {
weak var delegate: SplashScreenVMProtocol!
private let dataManager = DataManagement()
private let coreDataManager = CoreDataManagement()
lazy var itemsCount = coreDataManager.getRecords("Categories").count
lazy var timestamp = coreDataManager.getRecords("Timestamp")
init(){}
func setUpData() {
dataManager.fetchData(timestamp: 0 ) { (err, res) in
//dataManager.fetchData(timestamp: timestamp.count == 0 ? 0 : timestamp[0].value(forKey: "time") as! Int64) { (err, res) in
//print("categories count: \(self.coreDataManager.getRecords("Categories").count) and artciles count \(self.coreDataManager.getRecords("Articles").count)")
if(err != nil) {
print("Error: \(String(describing: err))");
self.delegate.failedFetchData()
return
}
self.coreDataManager.setTimestamp()
self.delegate.fetchDataSuccessfuly()
}
}
}
打开应用程序时的第一个视图SplashScreenController:
import UIKit
import Alamofire
class SplashScreenController: UIViewController, SplashScreenVMProtocol {
@IBOutlet weak var loadSpinner: UIActivityIndicatorView!
let splashScreenVM = SplashScreenVM()
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
lazy var MainController = storyBoard.instantiateViewController(withIdentifier: "MainVC")
override func viewDidLoad() {
super.viewDidLoad()
splashScreenVM.delegate = self //Looks like something wrong with this
print("apapapaap \(splashScreenVM.delegate)")
loadSpinner.hidesWhenStopped = true
loadSpinner.startAnimating()
switch Reachability.isConnectedToNetwork() {
case true:
splashScreenVM.setUpData()
case false:
self.loadSpinner.stopAnimating()
splashScreenVM.itemsCount == 0 ? print("butinai reikia intiko") : print("keliaujam i pagr.meniu")
}
}
func fetchDataSuccessfuly() {
self.loadSpinner.stopAnimating()
self.present(MainController, animated: true, completion: nil)
}
func failedFetchData() {
self.loadSpinner.stopAnimating()
if(splashScreenVM.itemsCount != 0) {
self.present(MainController, animated: true, completion: nil)
}
return
}
}
我做错了什么?我的弱变量代表:SplashScreenVMProtocol!返回nil。当应用再次苏醒时,是从头开始启动应用的更好方法吗?
答案 0 :(得分:0)
您没有在applicationWillEnterForeground中保留您的splashScreen变量。您将splashScreen视图设置为子视图,但是splashScreen本身只是一个局部变量。 当它超出范围时,对象将被释放。
您的数据访问正在异步进行,因此当它完成时,原始的splashScreen对象已经被释放并且不再存在。
有些东西需要保留在splashScreen上。
答案 1 :(得分:0)
好了,我解决了这个问题,也许...刚从weak var delegate: SplashScreenVMProtocol!
更改为var delegate: SplashScreenVMProtocol!
,并且效果很好,但是在控制台中却得到了这样的提示:“建议不要在分离的视图控制器上呈现视图控制器”