简体   繁体   中英

iOS: Force to cancel Operation in NSOperationQueue

I need to cancel all the operations in the NSOperationQueue immediately.

Consider my scenario,

I have to hit my server continuously ie I will be calling my server whenever user types in the textbox. After user completes his input I have to hit final api call. So I create one NSOperation for single API hit. While user types in the textbox. I create NSOperation object and add that in NSOperationQueue. After detecting that user completely his input, I cancelled all the operation in the queue and hit my final api. The Problem is some operations are not cancelled immediately. So my final api hit is not called immediately. It is waiting for some time (all operation have to finish) and then it called.

FYI,

myOperationQueue.cancelAllOperations()

In Operation start method I have this code

let session = URLSession.shared
let task = session.dataTask(with: urlRequest, completionHandler: { (data, urlResponse, error) -> Void in
})
task.resume()

Please provide me the best way to call my final API immediately.

The apple documentation about the cancellAllOperations method, it clearly explains your situation.

Canceling the operations does not automatically remove them from the queue or stop those that are currently executing. For operations that are queued and waiting execution, the queue must still attempt to execute the operation before recognizing that it is canceled and moving it to the finished state. For operations that are already executing, the operation object itself must check for cancellation and stop what it is doing so that it can move to the finished state. In both cases, a finished (or canceled) operation is still given a chance to execute its completion block before it is removed from the queue.

You have to cancel your task as well.

Implement a cancel override in your Operation subclass. This override cancels the task as well.

var task: URLSessionTask?

func scheduleTask() {
    let session = URLSession.shared

    ///Task is an instance variable 
    task = session.dataTask(with: urlRequest, completionHandler: { (data,     urlResponse, error) -> Void in
    })
    task?.resume()

}

public override func cancel() {
   task?.cancel()
   super.cancel()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM