forked from Alamofire/Alamofire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Session.swift
1264 lines (1117 loc) · 70.1 KB
/
Session.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Session.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common
/// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response
/// cache handling.
open class Session {
/// Shared singleton instance used by all `AF.request` APIs. Cannot be modified.
public static let `default` = Session()
/// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's
/// `delegate` handles `URLSessionDelegate` callbacks.
///
/// - Note: This instance should **NOT** be used to interact with the underlying `URLSessionTask`s. Doing so will
/// break internal Alamofire logic that tracks those tasks.
///
public let session: URLSession
/// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction.
public let delegate: SessionDelegate
/// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue.
public let rootQueue: DispatchQueue
/// Value determining whether this instance automatically calls `resume()` on all created `Request`s.
public let startRequestsImmediately: Bool
/// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its
/// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile
/// and test before introducing an additional queue.
public let requestQueue: DispatchQueue
/// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this
/// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined
/// to be a bottleneck. Always profile and test before introducing an additional queue.
public let serializationQueue: DispatchQueue
/// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a
/// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value.
public let interceptor: RequestInterceptor?
/// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning.
public let serverTrustManager: ServerTrustManager?
/// `RedirectHandler` instance used to provide customization for request redirection.
public let redirectHandler: RedirectHandler?
/// `CachedResponseHandler` instance used to provide customization of cached response handling.
public let cachedResponseHandler: CachedResponseHandler?
/// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s.
public let eventMonitor: CompositeEventMonitor
/// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default.
public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()]
/// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them.
var requestTaskMap = RequestTaskMap()
/// `Set` of currently active `Request`s.
var activeRequests: Set<Request> = []
/// Completion events awaiting `URLSessionTaskMetrics`.
var waitingCompletions: [URLSessionTask: () -> Void] = [:]
/// Creates a `Session` from a `URLSession` and other parameters.
///
/// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and
/// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer.
///
/// - Parameters:
/// - session: Underlying `URLSession` for this instance.
/// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
/// interaction.
/// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
/// serial queue.
/// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
/// by default. If set to `false`, all `Request`s created must have `.resume()` called.
/// on them for them to start.
/// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
/// will use the `rootQueue` as its `target`. A separate queue can be used if it's
/// determined request creation is a bottleneck, but that should only be done after
/// careful testing and profiling. `nil` by default.
/// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
/// queue will use the `rootQueue` as its `target`. A separate queue can be used if
/// it's determined response serialization is a bottleneck, but that should only be
/// done after careful testing and profiling. `nil` by default.
/// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
/// by default.
/// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
/// by default.
/// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
/// default.
/// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
/// `nil` by default.
/// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
/// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
public init(session: URLSession,
delegate: SessionDelegate,
rootQueue: DispatchQueue,
startRequestsImmediately: Bool = true,
requestQueue: DispatchQueue? = nil,
serializationQueue: DispatchQueue? = nil,
interceptor: RequestInterceptor? = nil,
serverTrustManager: ServerTrustManager? = nil,
redirectHandler: RedirectHandler? = nil,
cachedResponseHandler: CachedResponseHandler? = nil,
eventMonitors: [EventMonitor] = []) {
precondition(session.configuration.identifier == nil,
"Alamofire does not support background URLSessionConfigurations.")
precondition(session.delegateQueue.underlyingQueue === rootQueue,
"Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.")
self.session = session
self.delegate = delegate
self.rootQueue = rootQueue
self.startRequestsImmediately = startRequestsImmediately
self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue)
self.interceptor = interceptor
self.serverTrustManager = serverTrustManager
self.redirectHandler = redirectHandler
self.cachedResponseHandler = cachedResponseHandler
eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
delegate.eventMonitor = eventMonitor
delegate.stateProvider = self
}
/// Creates a `Session` from a `URLSessionConfiguration`.
///
/// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its
/// `delegateQueue`, and is the recommended initializer for most uses.
///
/// - Parameters:
/// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes
/// to this value after being passed to this initializer will have no effect.
/// `URLSessionConfiguration.af.default` by default.
/// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
/// interaction. `SessionDelegate()` by default.
/// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
/// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default.
/// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
/// by default. If set to `false`, all `Request`s created must have `.resume()` called.
/// on them for them to start.
/// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
/// will use the `rootQueue` as its `target`. A separate queue can be used if it's
/// determined request creation is a bottleneck, but that should only be done after
/// careful testing and profiling. `nil` by default.
/// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
/// queue will use the `rootQueue` as its `target`. A separate queue can be used if
/// it's determined response serialization is a bottleneck, but that should only be
/// done after careful testing and profiling. `nil` by default.
/// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
/// by default.
/// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
/// by default.
/// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
/// default.
/// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
/// `nil` by default.
/// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
/// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
delegate: SessionDelegate = SessionDelegate(),
rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
startRequestsImmediately: Bool = true,
requestQueue: DispatchQueue? = nil,
serializationQueue: DispatchQueue? = nil,
interceptor: RequestInterceptor? = nil,
serverTrustManager: ServerTrustManager? = nil,
redirectHandler: RedirectHandler? = nil,
cachedResponseHandler: CachedResponseHandler? = nil,
eventMonitors: [EventMonitor] = []) {
precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.")
// Retarget the incoming rootQueue for safety, unless it's the main queue, which we know is safe.
let serialRootQueue = (rootQueue === DispatchQueue.main) ? rootQueue : DispatchQueue(label: rootQueue.label,
target: rootQueue)
let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: serialRootQueue, name: "\(serialRootQueue.label).sessionDelegate")
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
self.init(session: session,
delegate: delegate,
rootQueue: serialRootQueue,
startRequestsImmediately: startRequestsImmediately,
requestQueue: requestQueue,
serializationQueue: serializationQueue,
interceptor: interceptor,
serverTrustManager: serverTrustManager,
redirectHandler: redirectHandler,
cachedResponseHandler: cachedResponseHandler,
eventMonitors: eventMonitors)
}
deinit {
finishRequestsForDeinit()
session.invalidateAndCancel()
}
// MARK: - All Requests API
/// Perform an action on all active `Request`s.
///
/// - Note: The provided `action` closure is performed asynchronously, meaning that some `Request`s may complete and
/// be unavailable by time it runs. Additionally, this action is performed on the instances's `rootQueue`,
/// so care should be taken that actions are fast. Once the work on the `Request`s is complete, any
/// additional work should be performed on another queue.
///
/// - Parameters:
/// - action: Closure to perform with all `Request`s.
public func withAllRequests(perform action: @escaping (Set<Request>) -> Void) {
rootQueue.async {
action(self.activeRequests)
}
}
/// Cancel all active `Request`s, optionally calling a completion handler when complete.
///
/// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled
/// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to
/// completion when cancelled.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default.
/// - completion: Closure to be called when all `Request`s have been cancelled.
public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) {
withAllRequests { requests in
requests.forEach { $0.cancel() }
queue.async {
completion?()
}
}
}
// MARK: - DataRequest
/// Closure which provides a `URLRequest` for mutation.
public typealias RequestModifier = (inout URLRequest) throws -> Void
struct RequestConvertible: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let parameters: Parameters?
let encoding: ParameterEncoding
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return try encoding.encode(request, with: parameters)
}
}
/// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
/// default.
/// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
/// `URLEncoding.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
let convertible = RequestConvertible(url: convertible,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
requestModifier: requestModifier)
return request(convertible, interceptor: interceptor)
}
struct RequestEncodableConvertible<Parameters: Encodable>: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let parameters: Parameters?
let encoder: ParameterEncoder
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return try parameters.map { try encoder.encode($0, into: request) } ?? request
}
}
/// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a
/// `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
/// `URLEncodedFormParameterEncoder.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
/// the provided parameters. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return request(convertible, interceptor: interceptor)
}
/// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
///
/// - Returns: The created `DataRequest`.
open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
let request = DataRequest(convertible: convertible,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self)
perform(request)
return request
}
// MARK: - DataStreamRequest
/// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the
/// `URLRequest`.
/// `URLEncodedFormParameterEncoder.default` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
/// the provided parameters. `nil` by default.
///
/// - Returns: The created `DataStream` request.
open func streamRequest<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataStreamRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return streamRequest(convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor)
}
/// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
/// the provided parameters. `nil` by default.
///
/// - Returns: The created `DataStream` request.
open func streamRequest(_ convertible: URLConvertible,
method: HTTPMethod = .get,
headers: HTTPHeaders? = nil,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil) -> DataStreamRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: Empty?.none,
encoder: URLEncodedFormParameterEncoder.default,
headers: headers,
requestModifier: requestModifier)
return streamRequest(convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
interceptor: interceptor)
}
/// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
/// is thrown while serializing stream `Data`. `false` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
/// by default.
///
/// - Returns: The created `DataStreamRequest`.
open func streamRequest(_ convertible: URLRequestConvertible,
automaticallyCancelOnStreamError: Bool = false,
interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
let request = DataStreamRequest(convertible: convertible,
automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self)
perform(request)
return request
}
// MARK: - DownloadRequest
/// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
/// `Destination`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
/// default.
/// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
/// Defaults to `URLEncoding.default`.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let convertible = RequestConvertible(url: convertible,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers,
requestModifier: requestModifier)
return download(convertible, interceptor: interceptor, to: destination)
}
/// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
/// a `RequestInterceptor`.
///
/// - Parameters:
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
/// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
/// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
/// Defaults to `URLEncodedFormParameterEncoder.default`.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download<Parameters: Encodable>(_ convertible: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
requestModifier: RequestModifier? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let convertible = RequestEncodableConvertible(url: convertible,
method: method,
parameters: parameters,
encoder: encoder,
headers: headers,
requestModifier: requestModifier)
return download(convertible, interceptor: interceptor, to: destination)
}
/// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
///
/// - Parameters:
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(_ convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let request = DownloadRequest(downloadable: .request(convertible),
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self,
destination: destination ?? DownloadRequest.defaultDestination)
perform(request)
return request
}
/// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
/// well as a `RequestInterceptor`, and a `Destination`.
///
/// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
/// Alamofire. The file will not be deleted until the system purges the temporary files.
///
/// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1),
/// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
/// generation logic where the data is written incorrectly and will always fail to resume the download. For more
/// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
///
/// - Parameters:
/// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
/// should be moved. `nil` by default.
///
/// - Returns: The created `DownloadRequest`.
open func download(resumingWith data: Data,
interceptor: RequestInterceptor? = nil,
to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
let request = DownloadRequest(downloadable: .resumeData(data),
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: self,
destination: destination ?? DownloadRequest.defaultDestination)
perform(request)
return request
}
// MARK: - UploadRequest
struct ParameterlessRequestConvertible: URLRequestConvertible {
let url: URLConvertible
let method: HTTPMethod
let headers: HTTPHeaders?
let requestModifier: RequestModifier?
func asURLRequest() throws -> URLRequest {
var request = try URLRequest(url: url, method: method, headers: headers)
try requestModifier?(&request)
return request
}
}
struct Upload: UploadConvertible {
let request: URLRequestConvertible
let uploadable: UploadableConvertible
func createUploadable() throws -> UploadRequest.Uploadable {
try uploadable.createUploadable()
}
func asURLRequest() throws -> URLRequest {
try request.asURLRequest()
}
}
// MARK: Data
/// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
///
/// - Parameters:
/// - data: The `Data` to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ data: Data,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
///
/// - Parameters:
/// - data: The `Data` to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ data: Data,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: File
/// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
/// components and `RequestInterceptor`.
///
/// - Parameters:
/// - fileURL: The `URL` of the file to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ fileURL: URL,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - fileURL: The `URL` of the file to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ fileURL: URL,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: InputStream
/// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - stream: The `InputStream` that provides the data to upload.
/// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
/// parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ stream: InputStream,
to convertible: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: convertible,
method: method,
headers: headers,
requestModifier: requestModifier)
return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
/// `RequestInterceptor`.
///
/// - Parameters:
/// - stream: The `InputStream` that provides the data to upload.
/// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(_ stream: InputStream,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager)
}
// MARK: MultipartFormData
/// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
/// `URLRequest` components and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` building closure.
/// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
/// provided parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
to url: URLConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: url,
method: method,
headers: headers,
requestModifier: requestModifier)
let formData = MultipartFormData(fileManager: fileManager)
multipartFormData(formData)
return upload(multipartFormData: formData,
with: convertible,
usingThreshold: encodingMemoryThreshold,
interceptor: interceptor,
fileManager: fileManager)
}
/// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
/// value, and a `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` building closure.
/// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
with request: URLRequestConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
let formData = MultipartFormData(fileManager: fileManager)
multipartFormData(formData)
return upload(multipartFormData: formData,
with: request,
usingThreshold: encodingMemoryThreshold,
interceptor: interceptor,
fileManager: fileManager)
}
/// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
/// and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` instance to upload.
/// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
/// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
/// written to disk before being uploaded. `.default` instance by default.
/// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
/// provided parameters. `nil` by default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: MultipartFormData,
to url: URLConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default,
requestModifier: RequestModifier? = nil) -> UploadRequest {
let convertible = ParameterlessRequestConvertible(url: url,
method: method,
headers: headers,
requestModifier: requestModifier)
let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
request: convertible,
multipartFormData: multipartFormData)
return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
}
/// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
/// value and `RequestInterceptor`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// - Parameters:
/// - multipartFormData: `MultipartFormData` instance to upload.
/// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
/// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
/// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
/// default.
/// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
/// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
/// default.
///
/// - Returns: The created `UploadRequest`.
open func upload(multipartFormData: MultipartFormData,
with request: URLRequestConvertible,
usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
interceptor: RequestInterceptor? = nil,
fileManager: FileManager = .default) -> UploadRequest {
let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
request: request,
multipartFormData: multipartFormData)
return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
}
// MARK: - Internal API
// MARK: Uploadable
func upload(_ uploadable: UploadRequest.Uploadable,
with convertible: URLRequestConvertible,
interceptor: RequestInterceptor?,
fileManager: FileManager) -> UploadRequest {
let uploadable = Upload(request: convertible, uploadable: uploadable)
return upload(uploadable, interceptor: interceptor, fileManager: fileManager)
}
func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest {
let request = UploadRequest(convertible: upload,
underlyingQueue: rootQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
fileManager: fileManager,
delegate: self)
perform(request)
return request
}
// MARK: Perform
/// Starts performing the provided `Request`.
///
/// - Parameter request: The `Request` to perform.
func perform(_ request: Request) {
rootQueue.async {
guard !request.isCancelled else { return }
self.activeRequests.insert(request)
self.requestQueue.async {
// Leaf types must come first, otherwise they will cast as their superclass.