Moya / Moya

Network abstraction layer written in Swift.
https://moya.github.io
MIT License
15.15k stars 1.99k forks source link

NSURLSessionTask priority #2174

Open ntnmrndn opened 3 years ago

ntnmrndn commented 3 years ago

Hello,

I was wondering wether Moya would consider adding support for prioritisation through NSURLSessionTask .priority property.

Do you have thoughts on the subject ?

ljluestc commented 7 months ago
import Moya
import Foundation

class PrioritizedMoyaProvider<Target>: MoyaProvider<Target> where Target: TargetType {

    override func request(_ target: Target, callbackQueue: DispatchQueue? = .none, progress: ProgressBlock? = .none, completion: @escaping Completion) -> Cancellable {
        let requestCompletion: Completion = { result in
            // Call the original completion handler with the result
            completion(result)
        }

        // Create a URLRequest using the target
        let urlRequest = try! target.urlRequest()

        // Create a URLSessionTask from the URLRequest
        let task = session.dataTask(with: urlRequest) { data, response, error in
            // Process the URLSessionTask response
            let result = Result<Response, MoyaError>.init(catching: {
                // Handle the response and error to create a Moya Response or Moya Error
                // Note: This logic should be adapted to fit your specific needs
                // For demonstration purposes, we'll just create a simple response
                let response = Response(statusCode: 200, data: data ?? Data())
                return response
            })

            // Call the request completion handler with the result
            requestCompletion(result)
        }

        // Set the task priority based on your logic
        // For demonstration purposes, we'll set it to high priority for all requests
        task.priority = URLSessionTask.highPriority

        // Start the URLSessionTask
        task.resume()

        // Return a Cancellable object representing the URLSessionTask
        return AnyCancellable(task)
    }
}