當我們的ios App跳轉至其他App時,例如設定或相簿等等
再從其他App回到我們的App時,到底該怎麼知道我們的App是否又被開起來了?
我們會先在欲返回前景的ViewController中的ViewDidLoad加入一個監聽器(Observer):
NotificationCenter.default.addObserver(self, selector: #selector(OpenMyAPP(notification:)), name: NSNotification.Name("OPEN") , object: nil)
然後在這個ViewController的class中加入要實作的function:
@objc func OpenMyAPP(notification: NSNotification) { print("Open!!!!!!") }
關於NotificationCenter的使用教學可以點此觀看唷
接著到AppDelegate中的applicationWillEnterForeground加入post NotificationCenter即可
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { //當App回到前景時 NotificationCenter.default.post(name: Notification.Name("OPEN"), object: nil) } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
沒有留言: