@@ -52,15 +52,8 @@ extension URLSession {
5252 assert ( parentProgress. cancellationHandler == nil , " The progress instance's cancellationHandler property must be nil " )
5353 }
5454
55- let request : URLRequest
56- do {
57- request = try builder. build ( )
58- } catch {
59- return . failure( . requestEncodingFailure( underlyingError: error) )
60- }
61-
6255 return await withCheckedContinuation { continuation in
63- let task = dataTask ( with : request ) { data, response, error in
56+ let completion : @ Sendable ( Data ? , URLResponse ? , Error ? ) -> Void = { data, response, error in
6457 let result : WordPressAPIResult < HTTPAPIResponse < Data > , E > = Self . parseResponse (
6558 data: data,
6659 response: response,
@@ -70,6 +63,16 @@ extension URLSession {
7063
7164 continuation. resume ( returning: result)
7265 }
66+
67+ let task : URLSessionTask
68+
69+ do {
70+ task = try self . task ( for: builder, completion: completion)
71+ } catch {
72+ continuation. resume ( returning: . failure( . requestEncodingFailure( underlyingError: error) ) )
73+ return
74+ }
75+
7376 task. resume ( )
7477
7578 if let parentProgress, parentProgress. totalUnitCount > parentProgress. completedUnitCount {
@@ -83,6 +86,32 @@ extension URLSession {
8386 }
8487 }
8588
89+ private func task(
90+ for builder: HTTPRequestBuilder ,
91+ completion: @escaping @Sendable ( Data ? , URLResponse ? , Error ? ) -> Void
92+ ) throws -> URLSessionTask {
93+ var request = try builder. build ( encodeMultipartForm: false )
94+
95+ // Use special `URLSession.uploadTask` API for multipart POST requests.
96+ if let multipart = builder. multipartForm, !multipart. isEmpty {
97+ let isBackgroundSession = configuration. identifier != nil
98+
99+ return try builder
100+ . encodeMultipartForm ( request: & request, forceWriteToFile: isBackgroundSession)
101+ . map (
102+ left: {
103+ uploadTask ( with: request, from: $0, completionHandler: completion)
104+ } ,
105+ right: {
106+ uploadTask ( with: request, fromFile: $0, completionHandler: completion)
107+ }
108+ )
109+ } else {
110+ // Use `URLSession.dataTask` for all other request
111+ return dataTask ( with: request, completionHandler: completion)
112+ }
113+ }
114+
86115 private static func parseResponse< E: LocalizedError > (
87116 data: Data ? ,
88117 response: URLResponse ? ,
0 commit comments