1 Reply
      Latest reply on Apr 19, 2019 12:22 AM by eskimo
      ovidaniel Level 1 Level 1 (0 points)

        hello I have an app in webkit, the app works well when it is in the foreground but in the background javascript completes its task and does not know how to start another one?

        I found this code, and with this it works, but the app is blocked, when I bring it back to the foreground, it does not stop for the while, who knows how to stop the while when the app comes back to the foreground? Thank you

         

        func applicationDidEnterBackground(_ application: UIApplication) {
           var finished = false
           var bgTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0);
           bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
               // Time is up.
               if bgTask != UIBackgroundTaskIdentifier.invalid {
                   // Do something to stop our background task or the app will be killed
                   finished = true
               }
           })
         
           // Perform your background task here
           print("The task has started")
           while !finished {
               print("Not finished")
               // when done, set finished to true
               // If that doesn't happen in time, the expiration handler will do it for us
           }
         
           // Indicate that it is complete
           application.endBackgroundTask(bgTask)
           if bgTask != UIBackgroundTaskIdentifier.invalid {
               // Do something to stop our background task or the app will be killed
               bgTask = UIBackgroundTaskIdentifier.invalid
               finished = true
           }
        }
        • Re: How to stop the while or how to make javascript work in the background?
          eskimo Apple Staff Apple Staff (11,625 points)

          Thanks for popping over to DevForums.

          The code you posted looks like it’s trying to block inside applicationDidEnterBackground(_:).  That will end badly.  That method is called on the main thread and is expected to return promptly, say, within a few tens of milliseconds.  Keep in mind that, because it’s running on the main thread, it prevents the main thread from doing anything else, and if it does that for too long you’ll eventually get killed by the watchdog.

          How you fix this depends on the bigger picture within your app.  You wrote:

          I have an app in webkit, the app works well when it is in the foreground but in the background javascript completes its task

          Is this JavaScript running within a web view?

          ps You can make your posts easier to read if you format code as code, using the <> button.

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"