Detect when home button is pressed iOS

前端 未结 6 738
半阙折子戏
半阙折子戏 2020-12-05 10:28

I have several iOS apps that all use the same port to listen for a network beacon. On the main view I use viewWillDisappear to close the port when another view is opened, w

6条回答
  •  被撕碎了的回忆
    2020-12-05 10:47

    In case of Swift User

    you can write it like this

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // code here...
    
        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "applicationWillResignActive:",
            name: UIApplicationWillResignActiveNotification,
            object: nil)
    }
    
    func applicationWillResignActive(notification: NSNotification) {
        print("I'm out of focus!")
    }
    

    also, Don't forget to close it when your app is terminate

    deinit {
    
        // code here...
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    

提交回复
热议问题