Search code examples
swiftuiviewpush-notificationanimatewithduration

How to removeFromSuperview from AppDelegate after 3 seconds in Swift


When I receive a push notification when app is active I create an UIView that appears. The issue is that view doesn't disspear but it stays there forever. This is the code:

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 65)

    let myView = UIView(frame: rect)

    let myViewLabel = UILabel(frame: rect)

    //myViewLabel.text = "Hola"

    myView.addSubview(myViewLabel)

    myView.backgroundColor = .orangeColor()

    if let aps = userInfo["aps"] as? NSDictionary {

        if let alert = aps["alert"] as? NSDictionary {

            if let message = alert["message"] as? NSString {

                //do stuff

            }
        } else if let alert = aps["alert"] as? NSString {

            if application.applicationState == .Active{

                AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

                myViewLabel.text = alert as String

                self.window?.addSubview(myView)

            }

        }
    }

}

Focus on

self.window?.addSubview(myView)

It stays there forever. I would like to do something like animateWithDuration to hide in 3 seconds but I don't find the way to do it from AppDelegate.

Any idea?


Solution

  • Declare a timer with 3 seconds

    var timer = NSTimer()
    
        timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: Selector("myFunc"), userInfo: nil, repeats: false)
    
        func myFunc(){
           // Called after 3 seconds
        }