简体   繁体   中英

How could I cancel several requests with Alamofire?

I want to cancel some requests, but not all. Now I make like this:

func cancelAllRequests() {
    let sessionManager = Alamofire.SessionManager.default
    sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in

        dataTasks.forEach { $0.cancel() }
        uploadTasks.forEach { $0.cancel() }
        downloadTasks.forEach { $0.cancel() }

    }
}

, but it cancel all requests. How could I distinguish requests?

You can write something like this to cancel specific task if you know request or url

func cancellRequest(for request: URLRequest) {
    Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
        _ = tasks
            .filter({ $0.originalRequest?.url?.path == request.url?.path })
            .map({ $0.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