3 Replies
      Latest reply on Jan 5, 2020 2:10 AM by eskimo
      garrett35 Level 1 Level 1 (0 points)

        Hey there,

         

        I wanted to use this to create a background task for my MacOS App.

         

        Unfortunately I don't knwo how to insert the code.

        I created

         

        let activity = NSBackgroundActivityScheduler(identifier: "com.example.MyApp.work")

         

        in AppDelegate and insert

         

        activity.repeats = true
        activity.interval = 30

         

        in applicationDidFinishLaunching() to initialize the values.

         

         

        But where is the right place to insert

         

        activity.schedule() { (completion: NSBackgroundActivityScheduler.CompletionHandler) in
                    // Perform the activity
                    print("Hello World")
                    self.completion(NSBackgroundActivityScheduler.Result.Finished)
                }

         

        in that way that this application will get a background task, which is not stopped if I quit (or leave) the application?

         

        Maybe that's an sutpid question but if so it sould be easy to answer ;-)

         

        Thanks a lot!

        • Re: Mac Background Scheduler
          eskimo Apple Staff Apple Staff (12,725 points)

          which is not stopped if I quit (or leave) the application?

          That’s not how NSBackgroundActivityScheduler works.  Rather, it assumes that your app is running and then it runs associated block when it’s a good time to perform the activity.  This is helpful, for example, if you need to index a big database but want to avoid doing that while the user is actively using the Mac.

          If you want this activity to run after the user has quit your app, you should move that work to a login item so that it’s always running.

          Share and Enjoy

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

          ps DTS is closed 21 Dec through 1 Jan.