pod-builder 1.9.3 → 2.0.0.beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +9 -0
  3. data/README.md +50 -13
  4. data/exe/pod_builder +39 -28
  5. data/lib/pod_builder/analyze.rb +32 -7
  6. data/lib/pod_builder/analyzer.rb +16 -0
  7. data/lib/pod_builder/command/build.rb +44 -161
  8. data/lib/pod_builder/command/build_all.rb +2 -2
  9. data/lib/pod_builder/command/clean.rb +34 -55
  10. data/lib/pod_builder/command/clear_lldbinit.rb +7 -3
  11. data/lib/pod_builder/command/deintegrate.rb +29 -7
  12. data/lib/pod_builder/command/generate_lfs.rb +3 -3
  13. data/lib/pod_builder/command/generate_podspec.rb +3 -2
  14. data/lib/pod_builder/command/info.rb +1 -1
  15. data/lib/pod_builder/command/init.rb +37 -14
  16. data/lib/pod_builder/command/install_sources.rb +21 -14
  17. data/lib/pod_builder/command/none.rb +2 -2
  18. data/lib/pod_builder/command/restore_all.rb +4 -4
  19. data/lib/pod_builder/command/switch.rb +137 -95
  20. data/lib/pod_builder/command/sync_podfile.rb +5 -3
  21. data/lib/pod_builder/command/update.rb +5 -6
  22. data/lib/pod_builder/command/update_lldbinit.rb +11 -9
  23. data/lib/pod_builder/configuration.rb +88 -13
  24. data/lib/pod_builder/core.rb +93 -12
  25. data/lib/pod_builder/info.rb +32 -98
  26. data/lib/pod_builder/install.rb +255 -195
  27. data/lib/pod_builder/licenses.rb +4 -4
  28. data/lib/pod_builder/podfile.rb +283 -73
  29. data/lib/pod_builder/podfile/post_actions.rb +9 -15
  30. data/lib/pod_builder/podfile_cp.rb +93 -0
  31. data/lib/pod_builder/podfile_item.rb +181 -82
  32. data/lib/pod_builder/podspec.rb +144 -135
  33. data/lib/pod_builder/rome/post_install.rb +240 -0
  34. data/lib/pod_builder/rome/pre_install.rb +6 -0
  35. data/lib/pod_builder/templates/build_podfile.template +3 -3
  36. data/lib/pod_builder/version.rb +1 -1
  37. data/pod-builder.gemspec +6 -6
  38. metadata +27 -80
  39. data/Example/Frameworks/PodBuilder.json +0 -32
  40. data/Example/PodBuilderExample.xcodeproj/project.pbxproj +0 -416
  41. data/Example/PodBuilderExample.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -7
  42. data/Example/PodBuilderExample.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +0 -8
  43. data/Example/PodBuilderExample.xcodeproj/project.xcworkspace/xcuserdata/tomas.xcuserdatad/UserInterfaceState.xcuserstate +0 -0
  44. data/Example/PodBuilderExample.xcodeproj/xcuserdata/tomas.xcuserdatad/xcschemes/xcschememanagement.plist +0 -14
  45. data/Example/PodBuilderExample.xcworkspace/contents.xcworkspacedata +0 -10
  46. data/Example/PodBuilderExample/AppDelegate.swift +0 -47
  47. data/Example/PodBuilderExample/Assets.xcassets/AppIcon.appiconset/Contents.json +0 -98
  48. data/Example/PodBuilderExample/Assets.xcassets/Contents.json +0 -6
  49. data/Example/PodBuilderExample/Base.lproj/LaunchScreen.storyboard +0 -25
  50. data/Example/PodBuilderExample/Base.lproj/Main.storyboard +0 -24
  51. data/Example/PodBuilderExample/Info.plist +0 -45
  52. data/Example/PodBuilderExample/ViewController.swift +0 -25
  53. data/Example/Podfile +0 -8
  54. data/Example/Podfile.lock +0 -16
  55. data/Example/Pods/Alamofire/LICENSE +0 -19
  56. data/Example/Pods/Alamofire/README.md +0 -242
  57. data/Example/Pods/Alamofire/Source/AFError.swift +0 -460
  58. data/Example/Pods/Alamofire/Source/Alamofire.swift +0 -465
  59. data/Example/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +0 -37
  60. data/Example/Pods/Alamofire/Source/MultipartFormData.swift +0 -580
  61. data/Example/Pods/Alamofire/Source/NetworkReachabilityManager.swift +0 -233
  62. data/Example/Pods/Alamofire/Source/Notifications.swift +0 -55
  63. data/Example/Pods/Alamofire/Source/ParameterEncoding.swift +0 -483
  64. data/Example/Pods/Alamofire/Source/Request.swift +0 -654
  65. data/Example/Pods/Alamofire/Source/Response.swift +0 -567
  66. data/Example/Pods/Alamofire/Source/ResponseSerialization.swift +0 -715
  67. data/Example/Pods/Alamofire/Source/Result.swift +0 -300
  68. data/Example/Pods/Alamofire/Source/ServerTrustPolicy.swift +0 -307
  69. data/Example/Pods/Alamofire/Source/SessionDelegate.swift +0 -725
  70. data/Example/Pods/Alamofire/Source/SessionManager.swift +0 -896
  71. data/Example/Pods/Alamofire/Source/TaskDelegate.swift +0 -466
  72. data/Example/Pods/Alamofire/Source/Timeline.swift +0 -136
  73. data/Example/Pods/Alamofire/Source/Validation.swift +0 -315
  74. data/Example/Pods/Manifest.lock +0 -16
  75. data/Example/Pods/Pods.xcodeproj/project.pbxproj +0 -673
  76. data/Example/Pods/Pods.xcodeproj/xcuserdata/tomas.xcuserdatad/xcschemes/Alamofire.xcscheme +0 -60
  77. data/Example/Pods/Pods.xcodeproj/xcuserdata/tomas.xcuserdatad/xcschemes/Pods-PodBuilderExample.xcscheme +0 -60
  78. data/Example/Pods/Pods.xcodeproj/xcuserdata/tomas.xcuserdatad/xcschemes/xcschememanagement.plist +0 -21
  79. data/Example/Pods/Target Support Files/Alamofire/Alamofire-dummy.m +0 -5
  80. data/Example/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch +0 -12
  81. data/Example/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h +0 -16
  82. data/Example/Pods/Target Support Files/Alamofire/Alamofire.modulemap +0 -6
  83. data/Example/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +0 -9
  84. data/Example/Pods/Target Support Files/Alamofire/Info.plist +0 -26
  85. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Info.plist +0 -26
  86. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-acknowledgements.markdown +0 -26
  87. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-acknowledgements.plist +0 -58
  88. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-dummy.m +0 -5
  89. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-frameworks.sh +0 -153
  90. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-resources.sh +0 -118
  91. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample-umbrella.h +0 -16
  92. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample.debug.xcconfig +0 -11
  93. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample.modulemap +0 -6
  94. data/Example/Pods/Target Support Files/Pods-PodBuilderExample/Pods-PodBuilderExample.release.xcconfig +0 -11
  95. data/lib/pod_builder/cocoapods/specification.rb +0 -27
@@ -1,233 +0,0 @@
1
- //
2
- // NetworkReachabilityManager.swift
3
- //
4
- // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
5
- //
6
- // Permission is hereby granted, free of charge, to any person obtaining a copy
7
- // of this software and associated documentation files (the "Software"), to deal
8
- // in the Software without restriction, including without limitation the rights
9
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- // copies of the Software, and to permit persons to whom the Software is
11
- // furnished to do so, subject to the following conditions:
12
- //
13
- // The above copyright notice and this permission notice shall be included in
14
- // all copies or substantial portions of the Software.
15
- //
16
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
- // THE SOFTWARE.
23
- //
24
-
25
- #if !os(watchOS)
26
-
27
- import Foundation
28
- import SystemConfiguration
29
-
30
- /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
31
- /// WiFi network interfaces.
32
- ///
33
- /// Reachability can be used to determine background information about why a network operation failed, or to retry
34
- /// network requests when a connection is established. It should not be used to prevent a user from initiating a network
35
- /// request, as it's possible that an initial request may be required to establish reachability.
36
- open class NetworkReachabilityManager {
37
- /// Defines the various states of network reachability.
38
- ///
39
- /// - unknown: It is unknown whether the network is reachable.
40
- /// - notReachable: The network is not reachable.
41
- /// - reachable: The network is reachable.
42
- public enum NetworkReachabilityStatus {
43
- case unknown
44
- case notReachable
45
- case reachable(ConnectionType)
46
- }
47
-
48
- /// Defines the various connection types detected by reachability flags.
49
- ///
50
- /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
51
- /// - wwan: The connection type is a WWAN connection.
52
- public enum ConnectionType {
53
- case ethernetOrWiFi
54
- case wwan
55
- }
56
-
57
- /// A closure executed when the network reachability status changes. The closure takes a single argument: the
58
- /// network reachability status.
59
- public typealias Listener = (NetworkReachabilityStatus) -> Void
60
-
61
- // MARK: - Properties
62
-
63
- /// Whether the network is currently reachable.
64
- open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
65
-
66
- /// Whether the network is currently reachable over the WWAN interface.
67
- open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
68
-
69
- /// Whether the network is currently reachable over Ethernet or WiFi interface.
70
- open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
71
-
72
- /// The current network reachability status.
73
- open var networkReachabilityStatus: NetworkReachabilityStatus {
74
- guard let flags = self.flags else { return .unknown }
75
- return networkReachabilityStatusForFlags(flags)
76
- }
77
-
78
- /// The dispatch queue to execute the `listener` closure on.
79
- open var listenerQueue: DispatchQueue = DispatchQueue.main
80
-
81
- /// A closure executed when the network reachability status changes.
82
- open var listener: Listener?
83
-
84
- open var flags: SCNetworkReachabilityFlags? {
85
- var flags = SCNetworkReachabilityFlags()
86
-
87
- if SCNetworkReachabilityGetFlags(reachability, &flags) {
88
- return flags
89
- }
90
-
91
- return nil
92
- }
93
-
94
- private let reachability: SCNetworkReachability
95
- open var previousFlags: SCNetworkReachabilityFlags
96
-
97
- // MARK: - Initialization
98
-
99
- /// Creates a `NetworkReachabilityManager` instance with the specified host.
100
- ///
101
- /// - parameter host: The host used to evaluate network reachability.
102
- ///
103
- /// - returns: The new `NetworkReachabilityManager` instance.
104
- public convenience init?(host: String) {
105
- guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
106
- self.init(reachability: reachability)
107
- }
108
-
109
- /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
110
- ///
111
- /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
112
- /// status of the device, both IPv4 and IPv6.
113
- ///
114
- /// - returns: The new `NetworkReachabilityManager` instance.
115
- public convenience init?() {
116
- var address = sockaddr_in()
117
- address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
118
- address.sin_family = sa_family_t(AF_INET)
119
-
120
- guard let reachability = withUnsafePointer(to: &address, { pointer in
121
- return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
122
- return SCNetworkReachabilityCreateWithAddress(nil, $0)
123
- }
124
- }) else { return nil }
125
-
126
- self.init(reachability: reachability)
127
- }
128
-
129
- private init(reachability: SCNetworkReachability) {
130
- self.reachability = reachability
131
- self.previousFlags = SCNetworkReachabilityFlags()
132
- }
133
-
134
- deinit {
135
- stopListening()
136
- }
137
-
138
- // MARK: - Listening
139
-
140
- /// Starts listening for changes in network reachability status.
141
- ///
142
- /// - returns: `true` if listening was started successfully, `false` otherwise.
143
- @discardableResult
144
- open func startListening() -> Bool {
145
- var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
146
- context.info = Unmanaged.passUnretained(self).toOpaque()
147
-
148
- let callbackEnabled = SCNetworkReachabilitySetCallback(
149
- reachability,
150
- { (_, flags, info) in
151
- let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info!).takeUnretainedValue()
152
- reachability.notifyListener(flags)
153
- },
154
- &context
155
- )
156
-
157
- let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
158
-
159
- listenerQueue.async {
160
- self.previousFlags = SCNetworkReachabilityFlags()
161
- self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
162
- }
163
-
164
- return callbackEnabled && queueEnabled
165
- }
166
-
167
- /// Stops listening for changes in network reachability status.
168
- open func stopListening() {
169
- SCNetworkReachabilitySetCallback(reachability, nil, nil)
170
- SCNetworkReachabilitySetDispatchQueue(reachability, nil)
171
- }
172
-
173
- // MARK: - Internal - Listener Notification
174
-
175
- func notifyListener(_ flags: SCNetworkReachabilityFlags) {
176
- guard previousFlags != flags else { return }
177
- previousFlags = flags
178
-
179
- listener?(networkReachabilityStatusForFlags(flags))
180
- }
181
-
182
- // MARK: - Internal - Network Reachability Status
183
-
184
- func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
185
- guard isNetworkReachable(with: flags) else { return .notReachable }
186
-
187
- var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
188
-
189
- #if os(iOS)
190
- if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
191
- #endif
192
-
193
- return networkStatus
194
- }
195
-
196
- func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
197
- let isReachable = flags.contains(.reachable)
198
- let needsConnection = flags.contains(.connectionRequired)
199
- let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
200
- let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
201
-
202
- return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
203
- }
204
- }
205
-
206
- // MARK: -
207
-
208
- extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
209
-
210
- /// Returns whether the two network reachability status values are equal.
211
- ///
212
- /// - parameter lhs: The left-hand side value to compare.
213
- /// - parameter rhs: The right-hand side value to compare.
214
- ///
215
- /// - returns: `true` if the two values are equal, `false` otherwise.
216
- public func ==(
217
- lhs: NetworkReachabilityManager.NetworkReachabilityStatus,
218
- rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
219
- -> Bool
220
- {
221
- switch (lhs, rhs) {
222
- case (.unknown, .unknown):
223
- return true
224
- case (.notReachable, .notReachable):
225
- return true
226
- case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
227
- return lhsConnectionType == rhsConnectionType
228
- default:
229
- return false
230
- }
231
- }
232
-
233
- #endif
@@ -1,55 +0,0 @@
1
- //
2
- // Notifications.swift
3
- //
4
- // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
5
- //
6
- // Permission is hereby granted, free of charge, to any person obtaining a copy
7
- // of this software and associated documentation files (the "Software"), to deal
8
- // in the Software without restriction, including without limitation the rights
9
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- // copies of the Software, and to permit persons to whom the Software is
11
- // furnished to do so, subject to the following conditions:
12
- //
13
- // The above copyright notice and this permission notice shall be included in
14
- // all copies or substantial portions of the Software.
15
- //
16
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
- // THE SOFTWARE.
23
- //
24
-
25
- import Foundation
26
-
27
- extension Notification.Name {
28
- /// Used as a namespace for all `URLSessionTask` related notifications.
29
- public struct Task {
30
- /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`.
31
- public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume")
32
-
33
- /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`.
34
- public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend")
35
-
36
- /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`.
37
- public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel")
38
-
39
- /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`.
40
- public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete")
41
- }
42
- }
43
-
44
- // MARK: -
45
-
46
- extension Notification {
47
- /// Used as a namespace for all `Notification` user info dictionary keys.
48
- public struct Key {
49
- /// User info dictionary key representing the `URLSessionTask` associated with the notification.
50
- public static let Task = "org.alamofire.notification.key.task"
51
-
52
- /// User info dictionary key representing the responseData associated with the notification.
53
- public static let ResponseData = "org.alamofire.notification.key.responseData"
54
- }
55
- }
@@ -1,483 +0,0 @@
1
- //
2
- // ParameterEncoding.swift
3
- //
4
- // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
5
- //
6
- // Permission is hereby granted, free of charge, to any person obtaining a copy
7
- // of this software and associated documentation files (the "Software"), to deal
8
- // in the Software without restriction, including without limitation the rights
9
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- // copies of the Software, and to permit persons to whom the Software is
11
- // furnished to do so, subject to the following conditions:
12
- //
13
- // The above copyright notice and this permission notice shall be included in
14
- // all copies or substantial portions of the Software.
15
- //
16
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
- // THE SOFTWARE.
23
- //
24
-
25
- import Foundation
26
-
27
- /// HTTP method definitions.
28
- ///
29
- /// See https://tools.ietf.org/html/rfc7231#section-4.3
30
- public enum HTTPMethod: String {
31
- case options = "OPTIONS"
32
- case get = "GET"
33
- case head = "HEAD"
34
- case post = "POST"
35
- case put = "PUT"
36
- case patch = "PATCH"
37
- case delete = "DELETE"
38
- case trace = "TRACE"
39
- case connect = "CONNECT"
40
- }
41
-
42
- // MARK: -
43
-
44
- /// A dictionary of parameters to apply to a `URLRequest`.
45
- public typealias Parameters = [String: Any]
46
-
47
- /// A type used to define how a set of parameters are applied to a `URLRequest`.
48
- public protocol ParameterEncoding {
49
- /// Creates a URL request by encoding parameters and applying them onto an existing request.
50
- ///
51
- /// - parameter urlRequest: The request to have parameters applied.
52
- /// - parameter parameters: The parameters to apply.
53
- ///
54
- /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
55
- ///
56
- /// - returns: The encoded request.
57
- func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
58
- }
59
-
60
- // MARK: -
61
-
62
- /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
63
- /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
64
- /// the HTTP body depends on the destination of the encoding.
65
- ///
66
- /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
67
- /// `application/x-www-form-urlencoded; charset=utf-8`.
68
- ///
69
- /// There is no published specification for how to encode collection types. By default the convention of appending
70
- /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
71
- /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
72
- /// square brackets appended to array keys.
73
- ///
74
- /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
75
- /// `true` as 1 and `false` as 0.
76
- public struct URLEncoding: ParameterEncoding {
77
-
78
- // MARK: Helper Types
79
-
80
- /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
81
- /// resulting URL request.
82
- ///
83
- /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
84
- /// requests and sets as the HTTP body for requests with any other HTTP method.
85
- /// - queryString: Sets or appends encoded query string result to existing query string.
86
- /// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
87
- public enum Destination {
88
- case methodDependent, queryString, httpBody
89
- }
90
-
91
- /// Configures how `Array` parameters are encoded.
92
- ///
93
- /// - brackets: An empty set of square brackets is appended to the key for every value.
94
- /// This is the default behavior.
95
- /// - noBrackets: No brackets are appended. The key is encoded as is.
96
- public enum ArrayEncoding {
97
- case brackets, noBrackets
98
-
99
- func encode(key: String) -> String {
100
- switch self {
101
- case .brackets:
102
- return "\(key)[]"
103
- case .noBrackets:
104
- return key
105
- }
106
- }
107
- }
108
-
109
- /// Configures how `Bool` parameters are encoded.
110
- ///
111
- /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior.
112
- /// - literal: Encode `true` and `false` as string literals.
113
- public enum BoolEncoding {
114
- case numeric, literal
115
-
116
- func encode(value: Bool) -> String {
117
- switch self {
118
- case .numeric:
119
- return value ? "1" : "0"
120
- case .literal:
121
- return value ? "true" : "false"
122
- }
123
- }
124
- }
125
-
126
- // MARK: Properties
127
-
128
- /// Returns a default `URLEncoding` instance.
129
- public static var `default`: URLEncoding { return URLEncoding() }
130
-
131
- /// Returns a `URLEncoding` instance with a `.methodDependent` destination.
132
- public static var methodDependent: URLEncoding { return URLEncoding() }
133
-
134
- /// Returns a `URLEncoding` instance with a `.queryString` destination.
135
- public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
136
-
137
- /// Returns a `URLEncoding` instance with an `.httpBody` destination.
138
- public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
139
-
140
- /// The destination defining where the encoded query string is to be applied to the URL request.
141
- public let destination: Destination
142
-
143
- /// The encoding to use for `Array` parameters.
144
- public let arrayEncoding: ArrayEncoding
145
-
146
- /// The encoding to use for `Bool` parameters.
147
- public let boolEncoding: BoolEncoding
148
-
149
- // MARK: Initialization
150
-
151
- /// Creates a `URLEncoding` instance using the specified destination.
152
- ///
153
- /// - parameter destination: The destination defining where the encoded query string is to be applied.
154
- /// - parameter arrayEncoding: The encoding to use for `Array` parameters.
155
- /// - parameter boolEncoding: The encoding to use for `Bool` parameters.
156
- ///
157
- /// - returns: The new `URLEncoding` instance.
158
- public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) {
159
- self.destination = destination
160
- self.arrayEncoding = arrayEncoding
161
- self.boolEncoding = boolEncoding
162
- }
163
-
164
- // MARK: Encoding
165
-
166
- /// Creates a URL request by encoding parameters and applying them onto an existing request.
167
- ///
168
- /// - parameter urlRequest: The request to have parameters applied.
169
- /// - parameter parameters: The parameters to apply.
170
- ///
171
- /// - throws: An `Error` if the encoding process encounters an error.
172
- ///
173
- /// - returns: The encoded request.
174
- public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
175
- var urlRequest = try urlRequest.asURLRequest()
176
-
177
- guard let parameters = parameters else { return urlRequest }
178
-
179
- if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
180
- guard let url = urlRequest.url else {
181
- throw AFError.parameterEncodingFailed(reason: .missingURL)
182
- }
183
-
184
- if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
185
- let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
186
- urlComponents.percentEncodedQuery = percentEncodedQuery
187
- urlRequest.url = urlComponents.url
188
- }
189
- } else {
190
- if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
191
- urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
192
- }
193
-
194
- urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
195
- }
196
-
197
- return urlRequest
198
- }
199
-
200
- /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
201
- ///
202
- /// - parameter key: The key of the query component.
203
- /// - parameter value: The value of the query component.
204
- ///
205
- /// - returns: The percent-escaped, URL encoded query string components.
206
- public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
207
- var components: [(String, String)] = []
208
-
209
- if let dictionary = value as? [String: Any] {
210
- for (nestedKey, value) in dictionary {
211
- components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
212
- }
213
- } else if let array = value as? [Any] {
214
- for value in array {
215
- components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
216
- }
217
- } else if let value = value as? NSNumber {
218
- if value.isBool {
219
- components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue))))
220
- } else {
221
- components.append((escape(key), escape("\(value)")))
222
- }
223
- } else if let bool = value as? Bool {
224
- components.append((escape(key), escape(boolEncoding.encode(value: bool))))
225
- } else {
226
- components.append((escape(key), escape("\(value)")))
227
- }
228
-
229
- return components
230
- }
231
-
232
- /// Returns a percent-escaped string following RFC 3986 for a query string key or value.
233
- ///
234
- /// RFC 3986 states that the following characters are "reserved" characters.
235
- ///
236
- /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
237
- /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
238
- ///
239
- /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
240
- /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
241
- /// should be percent-escaped in the query string.
242
- ///
243
- /// - parameter string: The string to be percent-escaped.
244
- ///
245
- /// - returns: The percent-escaped string.
246
- public func escape(_ string: String) -> String {
247
- let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
248
- let subDelimitersToEncode = "!$&'()*+,;="
249
-
250
- var allowedCharacterSet = CharacterSet.urlQueryAllowed
251
- allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
252
-
253
- var escaped = ""
254
-
255
- //==========================================================================================================
256
- //
257
- // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
258
- // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
259
- // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
260
- // info, please refer to:
261
- //
262
- // - https://github.com/Alamofire/Alamofire/issues/206
263
- //
264
- //==========================================================================================================
265
-
266
- if #available(iOS 8.3, *) {
267
- escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
268
- } else {
269
- let batchSize = 50
270
- var index = string.startIndex
271
-
272
- while index != string.endIndex {
273
- let startIndex = index
274
- let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
275
- let range = startIndex..<endIndex
276
-
277
- let substring = string[range]
278
-
279
- escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
280
-
281
- index = endIndex
282
- }
283
- }
284
-
285
- return escaped
286
- }
287
-
288
- private func query(_ parameters: [String: Any]) -> String {
289
- var components: [(String, String)] = []
290
-
291
- for key in parameters.keys.sorted(by: <) {
292
- let value = parameters[key]!
293
- components += queryComponents(fromKey: key, value: value)
294
- }
295
- return components.map { "\($0)=\($1)" }.joined(separator: "&")
296
- }
297
-
298
- private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
299
- switch destination {
300
- case .queryString:
301
- return true
302
- case .httpBody:
303
- return false
304
- default:
305
- break
306
- }
307
-
308
- switch method {
309
- case .get, .head, .delete:
310
- return true
311
- default:
312
- return false
313
- }
314
- }
315
- }
316
-
317
- // MARK: -
318
-
319
- /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
320
- /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
321
- public struct JSONEncoding: ParameterEncoding {
322
-
323
- // MARK: Properties
324
-
325
- /// Returns a `JSONEncoding` instance with default writing options.
326
- public static var `default`: JSONEncoding { return JSONEncoding() }
327
-
328
- /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
329
- public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
330
-
331
- /// The options for writing the parameters as JSON data.
332
- public let options: JSONSerialization.WritingOptions
333
-
334
- // MARK: Initialization
335
-
336
- /// Creates a `JSONEncoding` instance using the specified options.
337
- ///
338
- /// - parameter options: The options for writing the parameters as JSON data.
339
- ///
340
- /// - returns: The new `JSONEncoding` instance.
341
- public init(options: JSONSerialization.WritingOptions = []) {
342
- self.options = options
343
- }
344
-
345
- // MARK: Encoding
346
-
347
- /// Creates a URL request by encoding parameters and applying them onto an existing request.
348
- ///
349
- /// - parameter urlRequest: The request to have parameters applied.
350
- /// - parameter parameters: The parameters to apply.
351
- ///
352
- /// - throws: An `Error` if the encoding process encounters an error.
353
- ///
354
- /// - returns: The encoded request.
355
- public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
356
- var urlRequest = try urlRequest.asURLRequest()
357
-
358
- guard let parameters = parameters else { return urlRequest }
359
-
360
- do {
361
- let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
362
-
363
- if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
364
- urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
365
- }
366
-
367
- urlRequest.httpBody = data
368
- } catch {
369
- throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
370
- }
371
-
372
- return urlRequest
373
- }
374
-
375
- /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
376
- ///
377
- /// - parameter urlRequest: The request to apply the JSON object to.
378
- /// - parameter jsonObject: The JSON object to apply to the request.
379
- ///
380
- /// - throws: An `Error` if the encoding process encounters an error.
381
- ///
382
- /// - returns: The encoded request.
383
- public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
384
- var urlRequest = try urlRequest.asURLRequest()
385
-
386
- guard let jsonObject = jsonObject else { return urlRequest }
387
-
388
- do {
389
- let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
390
-
391
- if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
392
- urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
393
- }
394
-
395
- urlRequest.httpBody = data
396
- } catch {
397
- throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
398
- }
399
-
400
- return urlRequest
401
- }
402
- }
403
-
404
- // MARK: -
405
-
406
- /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
407
- /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
408
- /// field of an encoded request is set to `application/x-plist`.
409
- public struct PropertyListEncoding: ParameterEncoding {
410
-
411
- // MARK: Properties
412
-
413
- /// Returns a default `PropertyListEncoding` instance.
414
- public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
415
-
416
- /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
417
- public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
418
-
419
- /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
420
- public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
421
-
422
- /// The property list serialization format.
423
- public let format: PropertyListSerialization.PropertyListFormat
424
-
425
- /// The options for writing the parameters as plist data.
426
- public let options: PropertyListSerialization.WriteOptions
427
-
428
- // MARK: Initialization
429
-
430
- /// Creates a `PropertyListEncoding` instance using the specified format and options.
431
- ///
432
- /// - parameter format: The property list serialization format.
433
- /// - parameter options: The options for writing the parameters as plist data.
434
- ///
435
- /// - returns: The new `PropertyListEncoding` instance.
436
- public init(
437
- format: PropertyListSerialization.PropertyListFormat = .xml,
438
- options: PropertyListSerialization.WriteOptions = 0)
439
- {
440
- self.format = format
441
- self.options = options
442
- }
443
-
444
- // MARK: Encoding
445
-
446
- /// Creates a URL request by encoding parameters and applying them onto an existing request.
447
- ///
448
- /// - parameter urlRequest: The request to have parameters applied.
449
- /// - parameter parameters: The parameters to apply.
450
- ///
451
- /// - throws: An `Error` if the encoding process encounters an error.
452
- ///
453
- /// - returns: The encoded request.
454
- public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
455
- var urlRequest = try urlRequest.asURLRequest()
456
-
457
- guard let parameters = parameters else { return urlRequest }
458
-
459
- do {
460
- let data = try PropertyListSerialization.data(
461
- fromPropertyList: parameters,
462
- format: format,
463
- options: options
464
- )
465
-
466
- if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
467
- urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
468
- }
469
-
470
- urlRequest.httpBody = data
471
- } catch {
472
- throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
473
- }
474
-
475
- return urlRequest
476
- }
477
- }
478
-
479
- // MARK: -
480
-
481
- extension NSNumber {
482
- fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
483
- }