Reputation: 10815
Actually, I would say that both iOS ViewControllers
and Android Activities
have their lifecycle methods. For example an equivalent of ViewController.viewDidLoad()
is Activity.onCreate()
?
Else I still need to know the equivalent of the other :
OnStart()
OnRestart()
OnResume()
OnStop()
OnDestroy()
OnPause()
Upvotes: 73
Views: 30316
Reputation: 891
Here's how to get it done the Droid way:
import Foundation
import SwiftUI
import UIKit
public class AppleActivity : UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override public func viewDidLoad() -> Void {
super.viewDidLoad()
onCreate()
}
override public func viewWillAppear(_ animated: Bool) -> Void {
super.viewWillAppear(animated)
onStart()
}
public func initialize(){
NotificationCenter.default.addObserver(self, selector: #selector(onStart), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onResume), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onPause), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onStop), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onDestroy), name: UIApplication.willTerminateNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func onCreate() {
print("onCreate()")
}
@objc public func onStart() {
print("onStart()")
}
@objc public func onResume() {
print("onResume()")
}
@objc public func onPause() {
print("onPause()")
}
@objc public func onStop() {
print("onStop()")
}
@objc public func onDestroy() {
print("onDestroy()")
}
}
struct AppleActivityStruct : UIViewControllerRepresentable {
typealias UIViewControllerType = AppleActivity
public func makeUIViewController(context : Context) -> AppleActivity {
return AppleActivity()
}
public func updateUIViewController(_ uiViewController : AppleActivity, context : Context) {
// Update the view controller here if needed
}
}
Now you get all your callbacks triggered everytime you want it, no stress + no wahala
N.B
SinceonStart()
viaNotificationCenter.default.addObserver(self, selector: #selector(onStart), name: UIApplication.willEnterForegroundNotification, object: nil)
might not get invoked the first time the scene of the UIViewController is created, that's why a call to it is present withinviewWillAppear(_ animated: Bool)
Upvotes: 0
Reputation: 126455
This is a comparison between the lifecycle of Android vs iOS:
Upvotes: 193