-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOperation.swift
executable file
·589 lines (519 loc) · 19.9 KB
/
Operation.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
//
// Operation.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 8/2/15.
// Copyright © 2015 vluxe. All rights reserved.
//
import Foundation
enum HTTPOptError: ErrorType {
case InvalidRequest
}
/**
This protocol exist to allow easy and customizable swapping of a serializing format within an class methods of HTTP.
*/
public protocol HTTPSerializeProtocol {
/**
implement this protocol to support serializing parameters to the proper HTTP body or URL
-parameter request: The NSMutableURLRequest object you will modify to add the parameters to
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws
}
/**
Standard HTTP encoding
*/
public struct HTTPParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParameters(parameters)
}
}
/**
Send the data as a JSON body
*/
public struct JSONParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParametersAsJSON(parameters)
}
}
/**
All the things of an HTTP response
*/
public class Response {
/// The header values in HTTP response.
public var headers: Dictionary<String,String>?
/// The mime type of the HTTP response.
public var mimeType: String?
/// The suggested filename for a downloaded file.
public var suggestedFilename: String?
/// The body data of the HTTP response.
public var data: NSData {
return collectData
}
/// The status code of the HTTP response.
public var statusCode: Int?
/// The URL of the HTTP response.
public var URL: NSURL?
/// The Error of the HTTP response (if there was one).
public var error: NSError?
///Returns the response as a string
public var text: String? {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
///get the description of the response
public var description: String {
var buffer = ""
if let u = URL {
buffer += "URL:\n\(u)\n\n"
}
if let code = self.statusCode {
buffer += "Status Code:\n\(code)\n\n"
}
if let heads = headers {
buffer += "Headers:\n"
for (key, value) in heads {
buffer += "\(key): \(value)\n"
}
buffer += "\n"
}
if let t = text {
buffer += "Payload:\n\(t)\n"
}
return buffer
}
///private things
///holds the collected data
var collectData = NSMutableData()
///finish closure
var completionHandler:((Response) -> Void)?
//progress closure. Progress is between 0 and 1.
var progressHandler:((Float) -> Void)?
///This gets called on auth challenges. If nil, default handling is use.
///Returning nil from this method will cause the request to be rejected and cancelled
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for doing SSL pinning
var security: HTTPSecurity?
}
/**
The class that does the magic. Is a subclass of NSOperation so you can use it with operation queues or just a good ole HTTP request.
*/
public class HTTP: NSOperation {
/**
Get notified with a request finishes.
*/
public var onFinish:((Response) -> Void)? {
didSet {
if let handler = onFinish {
DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in
self.finish()
handler(response)
})
}
}
}
///This is for handling authenication
public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.auth = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.auth
}
}
///This is for doing SSL pinning
public var security: HTTPSecurity? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.security = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.security
}
}
///This is for monitoring progress
public var progress: ((Float) -> Void)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.progressHandler = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.progressHandler
}
}
///the actual task
var task: NSURLSessionDataTask!
private enum State: Int, Comparable {
/// The initial state of an `Operation`.
case Initialized
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case Ready
/// The `Operation` is executing.
case Executing
/// The `Operation` has finished executing.
case Finished
/// what state transitions are allowed
func canTransitionToState(target: State) -> Bool {
switch (self, target) {
case (.Initialized, .Ready):
return true
case (.Ready, .Executing):
return true
case (.Ready, .Finished):
return true
case (.Executing, .Finished):
return true
default:
return false
}
}
}
/// Private storage for the `state` property that will be KVO observed. don't set directly!
private var _state = State.Initialized
/// A lock to guard reads and writes to the `_state` property
private let stateLock = NSLock()
// use the KVO mechanism to indicate that changes to "state" affect ready, executing, finished properties
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state"]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state"]
}
// threadsafe
private var state: State {
get {
return stateLock.withCriticalScope {
_state
}
}
set(newState) {
willChangeValueForKey("state")
stateLock.withCriticalScope { Void -> Void in
guard _state != .Finished else {
print("Invalid! - Attempted to back out of Finished State")
return
}
assert(_state.canTransitionToState(newState), "Performing invalid state transition.")
_state = newState
}
didChangeValueForKey("state")
}
}
/**
creates a new HTTP request.
*/
public init(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) {
super.init()
task = session.dataTaskWithRequest(req)
DelegateManager.sharedInstance.addResponseForTask(task)
state = .Ready
}
//MARK: Subclassed NSOperation Methods
/// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous.
override public var asynchronous: Bool {
return true
}
// If the operation has been cancelled, "isReady" should return true
override public var ready: Bool {
switch state {
case .Initialized:
return cancelled
case .Ready:
return super.ready || cancelled
default:
return false
}
}
/// Returns if the task is current running.
override public var executing: Bool {
return state == .Executing
}
override public var finished: Bool {
return state == .Finished
}
/**
start/sends the HTTP task with a completionHandler. Use this when *NOT* using an NSOperationQueue.
*/
public func start(completionHandler:((Response) -> Void)) {
onFinish = completionHandler
start()
}
/**
Start the HTTP task. Make sure to set the onFinish closure before calling this to get a response.
*/
override public func start() {
if cancelled {
state = .Finished
return
}
state = .Executing
task.resume()
}
/**
Cancel the running task
*/
override public func cancel() {
task.cancel()
finish()
}
/**
Sets the task to finished.
If you aren't using the DelegateManager, you will have to call this in your delegate's URLSession:dataTask:didCompleteWithError: method
*/
public func finish() {
state = .Finished
}
/**
Check not executing or finished when adding dependencies
*/
override public func addDependency(operation: NSOperation) {
assert(state < .Executing, "Dependencies cannot be modified after execution has begun.")
super.addDependency(operation)
}
/**
Convenience bool to flag as operation userInitiated if necessary
*/
var userInitiated: Bool {
get {
return qualityOfService == .UserInitiated
}
set {
assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.")
qualityOfService = newValue ? .UserInitiated : .Default
}
}
/**
Class method to create a GET request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func GET(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HEAD request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a DELETE request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a POST request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PUT(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HTTP request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest }
if let handler = DelegateManager.sharedInstance.requestHandler {
handler(req)
}
req.verb = method
if let params = parameters {
try requestSerializer.serialize(req, parameters: params)
}
if let heads = headers {
for (key,value) in heads {
req.addValue(value, forHTTPHeaderField: key)
}
}
return HTTP(req)
}
/**
Set the global auth handler
*/
public class func globalAuth(handler: ((NSURLAuthenticationChallenge) -> NSURLCredential?)?) {
DelegateManager.sharedInstance.auth = handler
}
/**
Set the global security handler
*/
public class func globalSecurity(security: HTTPSecurity?) {
DelegateManager.sharedInstance.security = security
}
/**
Set the global request handler
*/
public class func globalRequest(handler: ((NSMutableURLRequest) -> Void)?) {
DelegateManager.sharedInstance.requestHandler = handler
}
}
// Simple operator functions to simplify the assertions used above.
private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
// Lock for getting / setting state safely
extension NSLock {
func withCriticalScope<T>(@noescape block: Void -> T) -> T {
lock()
let value = block()
unlock()
return value
}
}
/**
Absorb all the delegates methods of NSURLSession and forwards them to pretty closures.
This is basically the sin eater for NSURLSession.
*/
class DelegateManager: NSObject, NSURLSessionDataDelegate {
//the singleton to handle delegate needs of NSURLSession
static let sharedInstance = DelegateManager()
/// this is for global authenication handling
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for global SSL pinning
var security: HTTPSecurity?
/// this is for global request handling
var requestHandler:((NSMutableURLRequest) -> Void)?
var taskMap = Dictionary<Int,Response>()
//"install" a task by adding the task to the map and setting the completion handler
func addTask(task: NSURLSessionTask, completionHandler:((Response) -> Void)) {
addResponseForTask(task)
if let resp = responseForTask(task) {
resp.completionHandler = completionHandler
}
}
//"remove" a task by removing the task from the map
func removeTask(task: NSURLSessionTask) {
taskMap.removeValueForKey(task.taskIdentifier)
}
//add the response task
func addResponseForTask(task: NSURLSessionTask) {
if taskMap[task.taskIdentifier] == nil {
taskMap[task.taskIdentifier] = Response()
}
}
//get the response object for the task
func responseForTask(task: NSURLSessionTask) -> Response? {
return taskMap[task.taskIdentifier]
}
//handle getting data
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
addResponseForTask(dataTask)
guard let resp = responseForTask(dataTask) else { return }
resp.collectData.appendData(data)
if resp.progressHandler != nil { //don't want the extra cycles for no reason
guard let taskResp = dataTask.response else { return }
progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length))
}
}
//handle task finishing
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
guard let resp = responseForTask(task) else { return }
resp.error = error
if let hresponse = task.response as? NSHTTPURLResponse {
resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>
resp.mimeType = hresponse.MIMEType
resp.suggestedFilename = hresponse.suggestedFilename
resp.statusCode = hresponse.statusCode
resp.URL = hresponse.URL
}
if let code = resp.statusCode where resp.statusCode > 299 {
resp.error = createError(code)
}
if let handler = resp.completionHandler {
handler(resp)
}
removeTask(task)
}
//handle authenication
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
var sec = security
var au = auth
if let resp = responseForTask(task) {
if let s = resp.security {
sec = s
}
if let a = resp.auth {
au = a
}
}
if let sec = sec where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let space = challenge.protectionSpace
if let trust = space.serverTrust {
if sec.isValid(trust, domain: space.host) {
completionHandler(.UseCredential, NSURLCredential(trust: trust))
return
}
}
completionHandler(.CancelAuthenticationChallenge, nil)
return
} else if let a = au {
let cred = a(challenge)
if let c = cred {
completionHandler(.UseCredential, c)
return
}
completionHandler(.RejectProtectionSpace, nil)
return
}
completionHandler(.PerformDefaultHandling, nil)
}
//upload progress
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard let resp = responseForTask(task) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent)
}
//download progress
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let resp = responseForTask(downloadTask) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: bytesWritten)
}
//handle progress
func progressHandler(response: Response, expectedLength: Int64, currentLength: Int64) {
guard let handler = response.progressHandler else { return }
let slice = Float(1.0)/Float(expectedLength)
handler(slice*Float(currentLength))
}
/**
Create an error for response you probably don't want (400-500 HTTP responses for example).
-parameter code: Code for error.
-returns An NSError.
*/
private func createError(code: Int) -> NSError {
let text = HTTPStatusCode(statusCode: code).statusDescription
return NSError(domain: "HTTP", code: code, userInfo: [NSLocalizedDescriptionKey: text])
}
}
/**
Handles providing singletons of NSURLSession.
*/
class SharedSession {
static let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
static let ephemeralSession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
}