Search code examples
iosswiftfunctionbackground-process

Swift: How to make a function that loads something while the user uses the app?


I have a function that takes over a minute to run. I want this function to be running whenever the user isn't doing anything but as soon as the user makes an interaction the function stops and the user can do the interaction as normal.

I have no idea how to go about this or if it's even possible.

(The function that takes 1 minute is making random routes around a grid and just keeps making loads of false ones until one works. It's not the most effective thing but I have tried to rewrite it and can't.)


Solution

  • This is in Objective C

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Background execution
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI Update
        });
    });
    

    This is in Swift 3

    DispatchQueue.global(qos: .background).async {
        // Background execution
        DispatchQueue.main.async {
            // UI Update
        }
    }
    

    Use this to do stuff in the background while user can still use the app. There are other ways to do this like NSOperationQueue and also you can use delegate and completion handlers with this but for a novice developer, this will be the easiest approach.