-
Notifications
You must be signed in to change notification settings - Fork 1
/
Pidgey.swift
375 lines (309 loc) · 11 KB
/
Pidgey.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
import Foundation
public enum HTTPMethod : String{
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case HEAD = "HEAD"
case OPTIONS = "OPTIONS"
case PATCH = "PATCH"
public func contentTypeRequired() -> Bool
{
switch self {
case .GET, .HEAD, .DELETE:
return false
default:
return true
}
}
}
protocol HeaderName {
static var headerName: String {get}
}
public enum Header {
enum ContentType: String, HeaderName {
static var headerName: String {return "Content-Type"}
case JSON = "application/json"
case Form = "application/x-www-form-urlencoded"
}
enum Accept: String, HeaderName {
static var headerName: String {return "Accept"}
case JSON = "application/json"
case XML = "application/xml"
case Text = "application/text"
}
enum Authorization: HeaderName {
static var headerName: String {return "Authorization"}
}
}
public enum Result<T> {
case Success(T)
case Failure(ErrorType)
}
internal enum PidgeyError: ErrorType {
case InvalidURL
}
public class PidgeyBird: NSObject {
public class var sharedInstance: PidgeyBird {
struct Static {
static let instance = PidgeyBird()
}
return Static.instance
}
private var session: NSURLSession!
private var requests: [PidgeyRequest] = []
override init(){
super.init()
setupSession()
}
private func setupSession()
{
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: config)
}
private func request(url:String, method: HTTPMethod, params: [String: AnyObject]?, queryParams:[String: String]?) throws -> PidgeyRequest
{
guard let url = NSURL(string: url) else {
throw PidgeyError.InvalidURL
}
let request = PidgeyRequest(url: url, method: method)
request.pidgey = self
request.queryParams = queryParams
request.params = params
return request
}
public func GET(url:String, queryParams:[String:String]?) throws -> PidgeyRequest
{
let request = try self.request(url, method: .GET, params:nil,queryParams:queryParams)
return request
}
public func HEAD(url:String, queryParams:[String:String]?) throws -> PidgeyRequest
{
let request = try self.request(url, method: .HEAD, params:nil,queryParams:queryParams)
return request
}
public func OPTIONS(url:String, queryParams:[String:String]?) throws -> PidgeyRequest
{
let request = try self.request(url, method: .OPTIONS, params:nil,queryParams:queryParams)
return request
}
public func POST(url:String, params:[String:AnyObject], queryParams:[String:String]? = nil) throws -> PidgeyRequest
{
let request = try self.request(url, method: .POST, params: params, queryParams:queryParams)
return request
}
public func PUT(url:String, params:[String:AnyObject], queryParams:[String:String]? = nil) throws -> PidgeyRequest
{
let request = try self.request(url, method: .PUT, params: params, queryParams:queryParams)
return request
}
public func DELETE(url:String, params:[String:AnyObject], queryParams:[String:String]? = nil) throws -> PidgeyRequest
{
let request = try self.request(url, method: .DELETE, params: params, queryParams:queryParams)
return request
}
}
extension PidgeyBird {
public func requestWithID(requestID: Int) -> PidgeyRequest?{
let filteredRequests = requests.filter {$0.taskIdentifier == requestID}
return filteredRequests.first
}
public func cancelAllRequests(){
requests.forEach { (request:PidgeyRequest) in
request.cancel()
}
}
}
public enum PidgeyRequestSerializationMode {
case HTTP
case JSON
}
public class PidgeyRequest
{
private weak var pidgey: PidgeyBird?
private var originalURL: NSURL
public var urlRequest: NSMutableURLRequest
public var task: NSURLSessionTask?
private var params: [String:AnyObject]?
private var queryParams: [String: String]?
public var requestSerializationMode: PidgeyRequestSerializationMode = .HTTP
private var requestBody: NSData? {
return urlRequest.HTTPBody
}
public var taskIdentifier: Int? {
return task?.taskIdentifier
}
init(url: NSURL, method: HTTPMethod)
{
originalURL = url
urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPMethod = method.rawValue
}
public func resume(completion:(response:PidgeyResponse?, error:NSError?)->())
{
setQueryParams()
setRequestBody()
setContentType()
let session = pidgey?.session
pidgey?.requests.append(self)
task = session?.dataTaskWithRequest(urlRequest, completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) in
if let error = error {
completion(response: nil, error: error)
return
}
let pidgeyResponse = PidgeyResponse(request: self, data: data, urlResponse: response as? NSHTTPURLResponse)
completion(response:pidgeyResponse, error:error)
})
task?.resume()
}
public func cancel(){
task?.cancel()
}
}
extension PidgeyRequest {
private func setContentType()
{
// TODO: Set content type for form-multipart
if let method = HTTPMethod(rawValue: urlRequest.HTTPMethod) where method.contentTypeRequired() {
return
}
if requestSerializationMode == .JSON {
setHeader(Header.ContentType.headerName, value: Header.ContentType.JSON.rawValue)
}
else {
setHeader(Header.ContentType.headerName, value: Header.ContentType.Form.rawValue)
}
}
private func setRequestBody()
{
urlRequest.HTTPBody = serializeParams()
}
private func setQueryParams()
{
let queryParams = self.queryParams ?? [:]
let components = NSURLComponents(URL: originalURL, resolvingAgainstBaseURL: false)
var newQueryItems: [NSURLQueryItem] = []
for (key, value) in queryParams {
let queryItem = NSURLQueryItem(name: key, value: value)
newQueryItems.append(queryItem)
}
var existingQueryItems = components?.queryItems ?? []
existingQueryItems.appendContentsOf(newQueryItems)
components?.queryItems = existingQueryItems
urlRequest.URL = components?.URL
}
public func setHeader(header: String, value: String)
{
urlRequest.setValue(value, forHTTPHeaderField: header)
}
public func setHeaders(headers:[String:String])
{
urlRequest.allHTTPHeaderFields = nil
for (key, value) in headers {
setHeader(key, value: value)
}
}
private func addHeaders(headers:[String:String])
{
for (k,v) in headers {
setHeader(k, value: v)
}
}
public func setCookies(cookies:[String:String])
{
var httpCookies: [NSHTTPCookie] = []
for (k,v) in cookies {
if let cookie = NSHTTPCookie(properties: [
NSHTTPCookieName: k,
NSHTTPCookieValue: v,
NSHTTPCookieOriginURL: self.originalURL,
NSHTTPCookiePath: "/"
]) {
httpCookies.append(cookie)
}
}
let cookieHeaders = NSHTTPCookie.requestHeaderFieldsWithCookies(httpCookies)
addHeaders(cookieHeaders)
}
public func setAuthentication(username username:String, password: String)
{
let authString = "\(username):\(password)"
let utf8str = authString.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
setHeader(Header.Authorization.headerName, value: "Basic \(base64Encoded)")
}
}
}
extension PidgeyRequest {
private func serializeParams() -> NSData?
{
guard let params = params else {return nil}
var data: NSData?
if requestSerializationMode == .JSON {
data = try? NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions.PrettyPrinted])
}
else {
data = formEncodedParams()?.dataUsingEncoding(NSUTF8StringEncoding)
}
return data
}
private func formEncodedParams() -> String?
{
guard let params = params else {return nil}
var components: [(String, String)] = []
for (key, value) in params {
components += queryComponentsForParam(key, value: value)
}
return (components.map({return "\($0)=\($1)"}) as [String]).joinWithSeparator("&")
}
private func queryComponentsForParam(key: String, value: AnyObject) -> [(String,String)]
{
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponentsForParam("\(key)[\(nestedKey)]", value:value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponentsForParam("\(key)[]", value: value)
}
} else {
components.appendContentsOf([(percentEncodeString(key), percentEncodeString(value as? String))])
}
return components
}
private func percentEncodeString(string:String?) -> String {
return string?.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? ""
}
}
public struct PidgeyResponse {
private weak var request: PidgeyRequest?
public var urlResponse: NSHTTPURLResponse?
public var data: NSData?
public var json: AnyObject? {
if let data = data {
return try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
}
return nil
}
public var text: String? {
if let data = data {
return String(data: data, encoding: NSUTF8StringEncoding)
}
return nil
}
public var statusCode: Int? {
return urlResponse?.statusCode
}
public var headers: [String: String]{
return urlResponse?.allHeaderFields as? [String: String] ?? [:]
}
init(request: PidgeyRequest, data: NSData?, urlResponse: NSHTTPURLResponse?) {
self.data = data
self.urlResponse = urlResponse
self.request = request
}
}
public let Pidgey = PidgeyBird.sharedInstance