按下主页按钮时检测iOS

时间:2012-04-25 22:15:37

标签: iphone ios ipad ios5

我有几个iOS应用程序都使用相同的端口来侦听网络信标。在主视图中,我使用viewWillDisappear在打开另一个视图时关闭端口,这很有效。然后我注意到如果我从主视图控制器按下主页按钮而没有打开另一个视图来关闭端口,那么端口保持打开状态,而我的其他应用程序不再能够监听该端口。然后我尝试使用viewWillUnload,但是当我按下主页按钮时似乎没有调用它。

-(void)viewWillUnload
{
    //[super viewWillUnload];
    NSLog(@"View will unload");
    [udpSocket close];
    udpSocket = nil;
}

视图将卸载从未显示在控制台中,这使我相信该方法永远不会被调用。

有没有办法检测何时按下主页按钮,这样我可以关闭我的端口?

6 个答案:

答案 0 :(得分:44)

这些是你的选择

在你的app delegate:

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

答案 1 :(得分:31)

处理此问题的最简单方法是注册以在视图控制器中接收UIApplicationWillResignActiveNotification通知。

按下主页按钮,锁定并打电话时会发出该事件

- (void) applicationWillResign{
    NSLog(@"About to lose focus");
}

- (void) myVcInitMethod { 
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector(applicationWillResign)
        name:UIApplicationWillResignActiveNotification 
        object:nil];
}

答案 2 :(得分:10)

对于Swift用户

你可以像这样写

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!")
}

另外,请勿忘记在应用终止时关闭它

deinit {

    // code here...

    NSNotificationCenter.defaultCenter().removeObserver(self)
}

答案 3 :(得分:5)

除了内存不足外,通常不会调用

viewWillUnload。您最好实现application delegate methods applicationDidEnterBackground:applicationWillTerminate:并在那里完成工作或向应用程序中知道如何处理清理过程的部分发送通知。

答案 4 :(得分:5)

除了内存不足外,通常不会调用

viewWillUnload。请改用:

在您的App代表中:

- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

或者,如果您想在View Controller中使用代码:

- (void)viewDidDisappear:(BOOL)animated
{
//Put code here
}

- (void)viewWillDisappear:(BOOL)animated
{
//Put code here
}

答案 5 :(得分:4)

最好使用UIApplicationWillResignActiveUIApplicationDidBecomeActive,因为它们可以捕获“顶部矩形捕获和释放事件”#39; 我建议使用这个根类:

class VBase: UIViewController {
    fileprivate var listenersActivated = false
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        onStart()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        onStop()
        removeListeners()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        onStop()
        removeListeners()
    }

    internal func iniListeners() {
        if (!listenersActivated) {
            NotificationCenter.default.addObserver(self, selector: #selector(onStop), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(onStart), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
            listenersActivated = true
        } else {

        }
    }
    internal func removeListeners() {
        NotificationCenter.default.removeObserver(self)
        listenersActivated = false
    }
    internal func onStop() {

    }
    internal func onStart() {
        iniListeners()
    }

}

覆盖孩子内部的onStop()onStart()以捕捉所有观看外观/消失

即,

class SomeViewController: VBase {

...
    override func onStart() {
        super.onStart()
        someFunctionToInitialize()
    }
    override func onStop() {
        super.onStop()
        stopTimer()
        someFunctionToDesctruction()
    }
}