Search code examples
swiftmultithreadingfunctionreturnbackground-process

Swift - Exit function with background thread inside


I have a function that does some looping in the background and update the UI:

func doSomething() {
    DispatchQueue.global(qos: .userInteractive).async {
        for ... {
            if ... {
                ...
                DispatchQueue.main.async {
                    //Update UI
                    ...

                    if ... {
                        // Show UIAlert
                        //Exit function
                    }
                }
            }
        }
    }
} 

I want to exit the function (hence cancelling the background thread). If I use return, the alert shows up but the background thread keeps looping data to the end. I think the reason is that when swapping to the main thread, I am out of scope of the function.

I am new to Swift multi-threading, so any Idea?


Solution

  • As far as I know if you want to stop execution of for loop which is running on background thread, then you have to stop it from background thread itself which you are trying to stop from main thread block of code. try something line below :

    func doSomething() {
    
    var continueForLoop = true
    
    DispatchQueue.global(qos: .userInteractive).async {
        for ... {
            if ... && continueForLoop{
                ...
                DispatchQueue.main.sync {
                    //Update UI
                    ...
    
                    if ... {
                        // Show UIAlert
                        //Exit function
                        continueForLoop = false
                    }
                }
            }else{
               break;
            }
        }
    }
    

    }

    P.S. to understand multithreading in iOS go thought this link : iOS Concurrency Note: try to understand the multithreading part only as code contains old swift syntaxes.