我想从第一个视图重新启动应用程序:
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()
}
}
}
应用程序打开时的第一个视图启动屏幕控制器:
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
}
}
我做错了什么?我的弱var委托:SplashScreenVMProtocol!返回零。当应用程序再次唤醒时,是否可以从启动应用程序启动应用程序?
您没有在applicationWillEnterForeground中保留splashScreen变量。您将splashScreen视图设置为子视图,但splashScreen本身只是一个局部变量。当它超出范围时,对象将被释放。
您的数据访问是异步发生的,因此当它完成时,原始的splashScreen对象已经被释放并且不再存在。
有些东西需要保留在splashScreen上。
好吧,我解决了这个问题,也许......刚刚从weak var delegate: SplashScreenVMProtocol!
改为var delegate: SplashScreenVMProtocol!
并且工作得很好但是在控制台我得到这个“不鼓励在分离视图控制器上呈现视图控制器”