检测应用程序何时进入我的视图的背景时,最好的方法是什么?

时间:2012-01-25 23:16:35

标签: ios nstimer

我有一个使用NSTimer执行某些代码的视图控制器。

什么是检测应用程序何时进入后台的最佳方法,以便我可以暂停计时器?

10 个答案:

答案 0 :(得分:157)

当应用进入后台接收通知时,您可以让任何课程感兴趣。这是将这些类与AppDelegate耦合的一个很好的替代方法。

初始化所述课程时:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];

回应通知

-(void)appWillResignActive:(NSNotification*)note
{

}
-(void)appWillTerminate:(NSNotification*)note
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

}

答案 1 :(得分:23)

  

在Swift 4.0中

override func viewDidLoad() {
    super.viewDidLoad()

    let app = UIApplication.shared

    //Register for the applicationWillResignActive anywhere in your app.
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: app)
}

@objc func applicationWillResignActive(notification: NSNotification) {

}

答案 2 :(得分:9)

在您的应用程序AppDelegate上,iOS将调用(void)applicationDidEnterBackground:(UIApplication *)application方法。你可以在那里停下你的计时器。

答案 3 :(得分:7)

对于那些希望在Swift中执行此操作的人:

init

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)

deinit

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)

回应通知:

dynamic private func applicationWillResignActive() {
    // Do things here
}

Apple鼓励我们尽可能避免在Swift中使用动态调度和Objective-C选择器,但这仍然是最方便的方法。

答案 4 :(得分:2)

迅速4.1:

我使用封闭版本:

-- Calc1.hs, using a CST

{-# OPTIONS_GHC -Wall #-}

module Calc1 where

import Data.Char
import Text.Parsec
import Text.Parsec.String

data Expr = TermE Term | PlusE Term Term            deriving (Show)
data Term = FactorT Factor | TimesT Factor Factor   deriving (Show)
data Factor = NumberF Int | ParenF Expr             deriving (Show)

lexeme :: Parser a -> Parser a
lexeme p = p <* spaces

symbol :: String -> Parser String
symbol = lexeme . string

expr :: Parser Expr
expr = do
  t1 <- term
  (PlusE t1 <$ symbol "+" <*> term)
    <|> pure (TermE t1)

term :: Parser Term
term = do
  f1 <- factor
  (TimesT f1 <$ symbol "*" <*> factor)
    <|> pure (FactorT f1)

factor :: Parser Factor
factor = NumberF . read <$> lexeme (many1 (satisfy isDigit))
    <|> ParenF <$> between (symbol "(") (symbol ")") expr

parseExpr :: String -> Expr
parseExpr pgm = case parse (spaces *> expr) "(string)" pgm of
  Right e -> e
  Left err -> error $ show err

data AExpr -- Abstract Expression
  = NumberA Int
  | PlusA AExpr AExpr
  | TimesA AExpr AExpr

aexpr :: Expr -> AExpr
aexpr (TermE t) = aterm t
aexpr (PlusE t1 t2) = PlusA (aterm t1) (aterm t2)

aterm :: Term -> AExpr
aterm (FactorT f) = afactor f
aterm (TimesT f1 f2) = TimesA (afactor f1) (afactor f2)

afactor :: Factor -> AExpr
afactor (NumberF n) = NumberA n
afactor (ParenF e) = aexpr e

interp :: AExpr -> Int
interp (NumberA n) = n
interp (PlusA e1 e2) = interp e1 + interp e2
interp (TimesA e1 e2) = interp e1 * interp e2

calc :: String -> Int
calc = interp . aexpr . parseExpr

-- Calc2.hs, with direct parsing to AST {-# OPTIONS_GHC -Wall #-} module Calc where import Data.Char import Text.Parsec import Text.Parsec.String lexeme :: Parser a -> Parser a lexeme p = p <* spaces symbol :: String -> Parser String symbol = lexeme . string expr :: Parser AExpr expr = do t1 <- term (PlusA t1 <$ symbol "+" <*> term) <|> pure t1 term :: Parser AExpr term = do f1 <- factor (TimesA f1 <$ symbol "*" <*> factor) <|> pure f1 factor :: Parser AExpr factor = NumberA . read <$> lexeme (many1 (satisfy isDigit)) <|> between (symbol "(") (symbol ")") expr parseExpr :: String -> AExpr parseExpr pgm = case parse (spaces *> expr) "(string)" pgm of Right e -> e Left err -> error $ show err data AExpr -- Abstract Expression = NumberA Int | PlusA AExpr AExpr | TimesA AExpr AExpr interp :: AExpr -> Int interp (NumberA n) = n interp (PlusA e1 e2) = interp e1 + interp e2 interp (TimesA e1 e2) = interp e1 * interp e2 calc :: String -> Int calc = interp . parseExpr 方法返回一个不透明的对象,需要在某个时候将其删除。

答案 5 :(得分:0)

您的应用代表上的

- (void)applicationWillResignActive:(UIApplication *)application。您还可以注册其他对象的UIApplicationWillResignActiveNotification通知。

但是,您不一定需要暂停计时器。如果您不做任何事情,应用程序将无论如何都会进入睡眠状态,并且不会执行任何代码。据推测,当你再次活动时,你的计时器会被激活(如果你这样做)。如果你需要做一些特别的事情,你可以注册“确实成为活跃的”委托方法和通知。

答案 6 :(得分:0)

只有旁注: 如果您注册一个控制器A以通知后台,请注意即使您(例如..)按下第二个控制器B并且您正在显示B,它也会被调用: 如果此行为不正确,最好在

中注册/取消注册

didAppear / WillDisappear。

答案 7 :(得分:0)

迅速4:

jQuery.getJSON('/cart.js', function(cart) { cart.items.each($('#line-total-'+this.id).html(Shopify.formatMoney(this.line_price).replace('$','£')););});

答案 8 :(得分:0)

这是使用闭包的更好解决方案

声明观察者

var backgroundObserver: NSObjectProtocol?

在viewDidLoad中初始化观察者

backgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] notification in
  // Do what you want to do when app would go to background/ resign active  
}

别忘了在deinit中删除观察者

deinit {
    if let observer = backgroundObserver {
        NotificationCenter.default.removeObserver(observer)
    } 
}

答案 9 :(得分:0)

在 Swift 5.1 中

    override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)

         NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    
         NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        }
    
    override func viewWillDisappear(_ animated: Bool) { 
        super.viewWillDisappear(animated)

        NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)

        NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
    }


@objc private func applicationWillResignActive() {
    }

    @objc private func applicationDidBecomeActive() {
    }