0001 // 0002 // Operation.swift 0003 // SwiftHTTP 0004 // 0005 // Created by Dalton Cherry on 8/2/15. 0006 // Copyright © 2015 vluxe. All rights reserved. 0007 // 0008 0009 import Foundation 0010 0011 enum HTTPOptError: ErrorType { 0012 case InvalidRequest
Operation.swift:386 guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest }0013 } 0014 0015 /** 0016 This protocol exist to allow easy and customizable swapping of a serializing format within an class methods of HTTP. 0017 */ 0018 public protocol HTTPSerializeProtocol
Operation.swift:386 guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest }{ 0019 0020 /** 0021 implement this protocol to support serializing parameters to the proper HTTP body or URL 0022 -parameter request: The NSMutableURLRequest object you will modify to add the parameters to 0023 -parameter parameters: The container (array or dictionary) to convert and append to the URL or Body 0024 */ 0025 func serialize
Operation.swift:31 public struct HTTPParameterSerializer: HTTPSerializeProtocol {Operation.swift:41 public struct JSONParameterSerializer: HTTPSerializeProtocol {Operation.swift:342 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:349 public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:356 public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:363 public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:371 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:378 public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:385 public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws 0026 } 0027 0028 /** 0029 Standard HTTP encoding 0030 */ 0031 public struct HTTPParameterSerializer
Operation.swift:392 try requestSerializer.serialize(req, parameters: params): HTTPSerializeProtocol { 0032 public init
Operation.swift:342 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:349 public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:356 public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:363 public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:371 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:378 public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:385 public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {() { } 0033 public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws { 0034 try request.appendParameters(parameters) 0035 } 0036 } 0037 0038 /** 0039 Send the data as a JSON body 0040 */ 0041 public struct JSONParameterSerializer: HTTPSerializeProtocol { 0042 public init() { } 0043 public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws { 0044 try request.appendParametersAsJSON(parameters) 0045 } 0046 } 0047 0048 /** 0049 All the things of an HTTP response 0050 */ 0051 public class Response
Operation.swift:342 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:349 public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:356 public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:363 public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:371 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:378 public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:385 public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {{ 0052 /// The header values in HTTP response. 0053 public var headers
Operation.swift:98 var completionHandler:((Response) -> Void)?Operation.swift:121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) inOperation.swift:118 public var onFinish:((Response) -> Void)? {Operation.swift:284 public func start(completionHandler:((Response) -> Void)) {Operation.swift:460 var taskMap = Dictionary<Int,Response>()Operation.swift:462 func addTask(task: NSURLSessionTask, completionHandler:((Response) -> Void)) {Operation.swift:477 taskMap[task.taskIdentifier] = Response()Operation.swift:481 func responseForTask(task: NSURLSessionTask) -> Response? {Operation.swift:562 func progressHandler(response: Response, expectedLength: Int64, currentLength: Int64) {: Dictionary<String,String>? 0054 /// The mime type of the HTTP response. 0055 public var mimeType
Operation.swift:81 if let heads = headers {Operation.swift:501 resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>: String? 0056 /// The suggested filename for a downloaded file. 0057 public var suggestedFilename
Operation.swift:502 resp.mimeType = hresponse.MIMEType: String? 0058 /// The body data of the HTTP response. 0059 public var data
Operation.swift:503 resp.suggestedFilename = hresponse.suggestedFilename: NSData { 0060 return collectData 0061 } 0062 /// The status code of the HTTP response. 0063 public var statusCode
Operation.swift:70 return NSString(data: data, encoding: NSUTF8StringEncoding) as? String: Int? 0064 /// The URL of the HTTP response. 0065 public var URL
Operation.swift:78 if let code = self.statusCode {Operation.swift:504 resp.statusCode = hresponse.statusCodeOperation.swift:507 if let code = resp.statusCode where resp.statusCode > 299 {Operation.swift:507 if let code = resp.statusCode where resp.statusCode > 299 {: NSURL? 0066 /// The Error of the HTTP response (if there was one). 0067 public var error
Operation.swift:75 if let u = URL {Operation.swift:505 resp.URL = hresponse.URL: NSError? 0068 ///Returns the response as a string 0069 public var text
Operation.swift:499 resp.error = errorOperation.swift:508 resp.error = createError(code): String? { 0070 return NSString(data: data, encoding: NSUTF8StringEncoding) as? String 0071 } 0072 ///get the description of the response 0073 public var description: String { 0074 var buffer = "" 0075 if let u = URL { 0076 buffer += "URL:\n\(u)\n\n" 0077 } 0078 if let code = self.statusCode { 0079 buffer += "Status Code:\n\(code)\n\n" 0080 } 0081 if let heads = headers { 0082 buffer += "Headers:\n" 0083 for (key, value) in heads { 0084 buffer += "\(key): \(value)\n" 0085 } 0086 buffer += "\n" 0087 } 0088 if let t = text { 0089 buffer += "Payload:\n\(t)\n" 0090 } 0091 return buffer 0092 } 0093 ///private things 0094 0095 ///holds the collected data 0096 var collectData
Operation.swift:88 if let t = text {= NSMutableData() 0097 ///finish closure 0098 var completionHandler
Operation.swift:60 return collectDataOperation.swift:489 resp.collectData.appendData(data)Operation.swift:492 progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length)):((Response) -> Void)? 0099 0100 //progress closure. Progress is between 0 and 1. 0101 var progressHandler
Operation.swift:465 resp.completionHandler = completionHandlerOperation.swift:510 if let handler = resp.completionHandler {:((Float) -> Void)? 0102 0103 ///This gets called on auth challenges. If nil, default handling is use. 0104 ///Returning nil from this method will cause the request to be rejected and cancelled 0105 var auth
Operation.swift:160 return resp.progressHandlerOperation.swift:156 resp.progressHandler = newValueOperation.swift:490 if resp.progressHandler != nil { //don't want the extra cycles for no reasonOperation.swift:563 guard let handler = response.progressHandler else { return }:((NSURLAuthenticationChallenge) -> NSURLCredential?)? 0106 0107 ///This is for doing SSL pinning 0108 var security
Operation.swift:136 return resp.authOperation.swift:132 resp.auth = newValueOperation.swift:524 if let a = resp.auth {: HTTPSecurity? 0109 } 0110 0111 /** 0112 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. 0113 */ 0114 public class HTTP
Operation.swift:148 return resp.securityOperation.swift:144 resp.security = newValueOperation.swift:521 if let s = resp.security {: NSOperation { 0115 /** 0116 Get notified with a request finishes. 0117 */ 0118 public var onFinish
Operation.swift:342 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:343 return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:349 public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:350 return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:356 public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:357 return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:363 public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:364 return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:371 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:372 return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:378 public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:379 return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:385 public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {Operation.swift:399 return HTTP(req)Operation.swift:425 private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:425 private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:429 private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:429 private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {:((Response) -> Void)? { 0119 didSet { 0120 if let handler = onFinish { 0121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in 0122 self.finish() 0123 handler(response) 0124 }) 0125 } 0126 } 0127 } 0128 ///This is for handling authenication 0129 public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? { 0130 set { 0131 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } 0132 resp.auth = newValue 0133 } 0134 get { 0135 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } 0136 return resp.auth 0137 } 0138 } 0139 0140 ///This is for doing SSL pinning 0141 public var security: HTTPSecurity? { 0142 set { 0143 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } 0144 resp.security = newValue 0145 } 0146 get { 0147 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } 0148 return resp.security 0149 } 0150 } 0151 0152 ///This is for monitoring progress 0153 public var progress: ((Float) -> Void)? { 0154 set { 0155 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return } 0156 resp.progressHandler = newValue 0157 } 0158 get { 0159 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil } 0160 return resp.progressHandler 0161 } 0162 } 0163 0164 ///the actual task 0165 var task
Operation.swift:120 if let handler = onFinish {Operation.swift:285 onFinish = completionHandler: NSURLSessionDataTask! 0166 0167 private enum State
Operation.swift:121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) inOperation.swift:135 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:131 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:147 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:143 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:159 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:155 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:245 task = session.dataTaskWithRequest(req)Operation.swift:246 DelegateManager.sharedInstance.addResponseForTask(task)Operation.swift:299 task.resume()Operation.swift:306 task.cancel(): Int, Comparable { 0168 /// The initial state of an `Operation`. 0169 case Initialized
Operation.swift:184 func canTransitionToState(target: State) -> Bool {Operation.swift:201 private var _state = State.InitializedOperation.swift:220 private var state: State {Operation.swift:333 assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.")Operation.swift:425 private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:425 private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:429 private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {Operation.swift:429 private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool {0170 0171 /** 0172 The `Operation`'s conditions have all been satisfied, and it is ready 0173 to execute. 0174 */ 0175 case Ready
Operation.swift:186 case (.Initialized, .Ready):Operation.swift:201 private var _state = State.InitializedOperation.swift:261 case .Initialized:0176 0177 /// The `Operation` is executing. 0178 case Executing
Operation.swift:186 case (.Initialized, .Ready):Operation.swift:188 case (.Ready, .Executing):Operation.swift:190 case (.Ready, .Finished):Operation.swift:247 state = .ReadyOperation.swift:264 case .Ready:0179 0180 /// The `Operation` has finished executing. 0181 case Finished
Operation.swift:188 case (.Ready, .Executing):Operation.swift:192 case (.Executing, .Finished):Operation.swift:274 return state == .ExecutingOperation.swift:298 state = .ExecutingOperation.swift:321 assert(state < .Executing, "Dependencies cannot be modified after execution has begun.")Operation.swift:333 assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.")0182 0183 /// what state transitions are allowed 0184 func canTransitionToState
Operation.swift:190 case (.Ready, .Finished):Operation.swift:192 case (.Executing, .Finished):Operation.swift:229 guard _state != .Finished else {Operation.swift:278 return state == .FinishedOperation.swift:294 state = .FinishedOperation.swift:314 state = .Finished(target: State) -> Bool { 0185 switch (self, target) { 0186 case (.Initialized, .Ready): 0187 return true 0188 case (.Ready, .Executing): 0189 return true 0190 case (.Ready, .Finished): 0191 return true 0192 case (.Executing, .Finished): 0193 return true 0194 default: 0195 return false 0196 } 0197 } 0198 } 0199 0200 /// Private storage for the `state` property that will be KVO observed. don't set directly! 0201 private var _state
Operation.swift:233 assert(_state.canTransitionToState(newState), "Performing invalid state transition.")= State.Initialized 0202 0203 /// A lock to guard reads and writes to the `_state` property 0204 private let stateLock
Operation.swift:223 _stateOperation.swift:229 guard _state != .Finished else {Operation.swift:233 assert(_state.canTransitionToState(newState), "Performing invalid state transition.")Operation.swift:234 _state = newState= NSLock() 0205 0206 // use the KVO mechanism to indicate that changes to "state" affect ready, executing, finished properties 0207 class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { 0208 return ["state"] 0209 } 0210 0211 class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { 0212 return ["state"] 0213 } 0214 0215 class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { 0216 return ["state"] 0217 } 0218 0219 // threadsafe 0220 private var state
Operation.swift:222 return stateLock.withCriticalScope {Operation.swift:228 stateLock.withCriticalScope { Void -> Void in: State { 0221 get { 0222 return stateLock.withCriticalScope { 0223 _state 0224 } 0225 } 0226 set(newState) { 0227 willChangeValueForKey("state") 0228 stateLock.withCriticalScope { Void -> Void in 0229 guard _state != .Finished else { 0230 print("Invalid! - Attempted to back out of Finished State") 0231 return 0232 } 0233 assert(_state.canTransitionToState(newState), "Performing invalid state transition.") 0234 _state = newState 0235 } 0236 didChangeValueForKey("state") 0237 } 0238 } 0239 0240 /** 0241 creates a new HTTP request. 0242 */ 0243 public init
Operation.swift:247 state = .ReadyOperation.swift:259 switch state {Operation.swift:274 return state == .ExecutingOperation.swift:278 return state == .FinishedOperation.swift:294 state = .FinishedOperation.swift:298 state = .ExecutingOperation.swift:314 state = .FinishedOperation.swift:321 assert(state < .Executing, "Dependencies cannot be modified after execution has begun.")Operation.swift:333 assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.")(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) { 0244 super.init() 0245 task = session.dataTaskWithRequest(req) 0246 DelegateManager.sharedInstance.addResponseForTask(task) 0247 state = .Ready 0248 } 0249 0250 //MARK: Subclassed NSOperation Methods 0251 0252 /// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous. 0253 override public var asynchronous: Bool { 0254 return true 0255 } 0256 0257 // If the operation has been cancelled, "isReady" should return true 0258 override public var ready: Bool { 0259 switch state { 0260 0261 case .Initialized: 0262 return cancelled 0263 0264 case .Ready: 0265 return super.ready || cancelled 0266 0267 default: 0268 return false 0269 } 0270 } 0271 0272 /// Returns if the task is current running. 0273 override public var executing: Bool { 0274 return state == .Executing 0275 } 0276 0277 override public var finished: Bool { 0278 return state == .Finished 0279 } 0280 0281 /** 0282 start/sends the HTTP task with a completionHandler. Use this when *NOT* using an NSOperationQueue. 0283 */ 0284 public func start(completionHandler:((Response) -> Void)) { 0285 onFinish = completionHandler 0286 start() 0287 } 0288 0289 /** 0290 Start the HTTP task. Make sure to set the onFinish closure before calling this to get a response. 0291 */ 0292 override public func start
Operation.swift:399 return HTTP(req)() { 0293 if cancelled { 0294 state = .Finished 0295 return 0296 } 0297 0298 state = .Executing 0299 task.resume() 0300 } 0301 0302 /** 0303 Cancel the running task 0304 */ 0305 override public func cancel() { 0306 task.cancel() 0307 finish() 0308 } 0309 /** 0310 Sets the task to finished. 0311 If you aren't using the DelegateManager, you will have to call this in your delegate's URLSession:dataTask:didCompleteWithError: method 0312 */ 0313 public func finish
Operation.swift:286 start()() { 0314 state = .Finished 0315 } 0316 0317 /** 0318 Check not executing or finished when adding dependencies 0319 */ 0320 override public func addDependency(operation: NSOperation) { 0321 assert(state < .Executing, "Dependencies cannot be modified after execution has begun.") 0322 super.addDependency(operation) 0323 } 0324 0325 /** 0326 Convenience bool to flag as operation userInitiated if necessary 0327 */ 0328 var userInitiated: Bool { 0329 get { 0330 return qualityOfService == .UserInitiated 0331 } 0332 set { 0333 assert(state < State.Executing, "Cannot modify userInitiated after execution has begun.") 0334 qualityOfService = newValue ? .UserInitiated : .Default 0335 } 0336 } 0337 0338 /** 0339 Class method to create a GET request that handles the NSMutableURLRequest and parameter encoding for you. 0340 */ 0341 public class func GET(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, 0342 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0343 return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0344 } 0345 0346 /** 0347 Class method to create a HEAD request that handles the NSMutableURLRequest and parameter encoding for you. 0348 */ 0349 public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0350 return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0351 } 0352 0353 /** 0354 Class method to create a DELETE request that handles the NSMutableURLRequest and parameter encoding for you. 0355 */ 0356 public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0357 return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0358 } 0359 0360 /** 0361 Class method to create a POST request that handles the NSMutableURLRequest and parameter encoding for you. 0362 */ 0363 public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0364 return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0365 } 0366 0367 /** 0368 Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you. 0369 */ 0370 public class func PUT(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, 0371 requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0372 return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0373 } 0374 0375 /** 0376 Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you. 0377 */ 0378 public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0379 return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer) 0380 } 0381 0382 /** 0383 Class method to create a HTTP request that handles the NSMutableURLRequest and parameter encoding for you. 0384 */ 0385 public class func New
Operation.swift:122 self.finish()Operation.swift:307 finish()(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP { 0386 guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest } 0387 if let handler = DelegateManager.sharedInstance.requestHandler { 0388 handler(req) 0389 } 0390 req.verb = method 0391 if let params = parameters { 0392 try requestSerializer.serialize(req, parameters: params) 0393 } 0394 if let heads = headers { 0395 for (key,value) in heads { 0396 req.addValue(value, forHTTPHeaderField: key) 0397 } 0398 } 0399 return HTTP(req) 0400 } 0401 0402 /** 0403 Set the global auth handler 0404 */ 0405 public class func globalAuth(handler: ((NSURLAuthenticationChallenge) -> NSURLCredential?)?) { 0406 DelegateManager.sharedInstance.auth = handler 0407 } 0408 0409 /** 0410 Set the global security handler 0411 */ 0412 public class func globalSecurity(security: HTTPSecurity?) { 0413 DelegateManager.sharedInstance.security = security 0414 } 0415 0416 /** 0417 Set the global request handler 0418 */ 0419 public class func globalRequest(handler: ((NSMutableURLRequest) -> Void)?) { 0420 DelegateManager.sharedInstance.requestHandler = handler 0421 } 0422 } 0423 0424 // Simple operator functions to simplify the assertions used above. 0425 private func <(lhs: HTTP.State, rhs: HTTP.State) -> Bool { 0426 return lhs.rawValue < rhs.rawValue 0427 } 0428 0429 private func ==(lhs: HTTP.State, rhs: HTTP.State) -> Bool { 0430 return lhs.rawValue == rhs.rawValue 0431 } 0432 0433 // Lock for getting / setting state safely 0434 extension NSLock { 0435 func withCriticalScope
Operation.swift:343 return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:350 return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:357 return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:364 return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:372 return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer)Operation.swift:379 return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer)<T>(@noescape block: Void -> T) -> T { 0436 lock() 0437 let value = block() 0438 unlock() 0439 return value 0440 } 0441 } 0442 0443 /** 0444 Absorb all the delegates methods of NSURLSession and forwards them to pretty closures. 0445 This is basically the sin eater for NSURLSession. 0446 */ 0447 class DelegateManager
Operation.swift:222 return stateLock.withCriticalScope {Operation.swift:228 stateLock.withCriticalScope { Void -> Void in: NSObject, NSURLSessionDataDelegate { 0448 //the singleton to handle delegate needs of NSURLSession 0449 static let sharedInstance
Operation.swift:121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) inOperation.swift:135 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:131 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:147 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:143 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:159 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:155 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:246 DelegateManager.sharedInstance.addResponseForTask(task)Operation.swift:387 if let handler = DelegateManager.sharedInstance.requestHandler {Operation.swift:406 DelegateManager.sharedInstance.auth = handlerOperation.swift:413 DelegateManager.sharedInstance.security = securityOperation.swift:420 DelegateManager.sharedInstance.requestHandler = handlerOperation.swift:449 static let sharedInstance = DelegateManager()Operation.swift:586 delegate: DelegateManager.sharedInstance, delegateQueue: nil)Operation.swift:588 delegate: DelegateManager.sharedInstance, delegateQueue: nil)= DelegateManager() 0450 0451 /// this is for global authenication handling 0452 var auth
Operation.swift:121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) inOperation.swift:135 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:131 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:147 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:143 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:159 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:155 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:246 DelegateManager.sharedInstance.addResponseForTask(task)Operation.swift:387 if let handler = DelegateManager.sharedInstance.requestHandler {Operation.swift:406 DelegateManager.sharedInstance.auth = handlerOperation.swift:413 DelegateManager.sharedInstance.security = securityOperation.swift:420 DelegateManager.sharedInstance.requestHandler = handlerOperation.swift:586 delegate: DelegateManager.sharedInstance, delegateQueue: nil)Operation.swift:588 delegate: DelegateManager.sharedInstance, delegateQueue: nil):((NSURLAuthenticationChallenge) -> NSURLCredential?)? 0453 0454 ///This is for global SSL pinning 0455 var security
Operation.swift:406 DelegateManager.sharedInstance.auth = handlerOperation.swift:519 var au = auth: HTTPSecurity? 0456 0457 /// this is for global request handling 0458 var requestHandler
Operation.swift:413 DelegateManager.sharedInstance.security = securityOperation.swift:518 var sec = security:((NSMutableURLRequest) -> Void)? 0459 0460 var taskMap
Operation.swift:387 if let handler = DelegateManager.sharedInstance.requestHandler {Operation.swift:420 DelegateManager.sharedInstance.requestHandler = handler= Dictionary<Int,Response>() 0461 //"install" a task by adding the task to the map and setting the completion handler 0462 func addTask
Operation.swift:471 taskMap.removeValueForKey(task.taskIdentifier)Operation.swift:476 if taskMap[task.taskIdentifier] == nil {Operation.swift:477 taskMap[task.taskIdentifier] = Response()Operation.swift:482 return taskMap[task.taskIdentifier](task: NSURLSessionTask, completionHandler:((Response) -> Void)) { 0463 addResponseForTask(task) 0464 if let resp = responseForTask(task) { 0465 resp.completionHandler = completionHandler 0466 } 0467 } 0468 0469 //"remove" a task by removing the task from the map 0470 func removeTask
Operation.swift:121 DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in(task: NSURLSessionTask) { 0471 taskMap.removeValueForKey(task.taskIdentifier) 0472 } 0473 0474 //add the response task 0475 func addResponseForTask
Operation.swift:513 removeTask(task)(task: NSURLSessionTask) { 0476 if taskMap[task.taskIdentifier] == nil { 0477 taskMap[task.taskIdentifier] = Response() 0478 } 0479 } 0480 //get the response object for the task 0481 func responseForTask
Operation.swift:246 DelegateManager.sharedInstance.addResponseForTask(task)Operation.swift:463 addResponseForTask(task)Operation.swift:487 addResponseForTask(dataTask)(task: NSURLSessionTask) -> Response? { 0482 return taskMap[task.taskIdentifier] 0483 } 0484 0485 //handle getting data 0486 func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { 0487 addResponseForTask(dataTask) 0488 guard let resp = responseForTask(dataTask) else { return } 0489 resp.collectData.appendData(data) 0490 if resp.progressHandler != nil { //don't want the extra cycles for no reason 0491 guard let taskResp = dataTask.response else { return } 0492 progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length)) 0493 } 0494 } 0495 0496 //handle task finishing 0497 func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { 0498 guard let resp = responseForTask(task) else { return } 0499 resp.error = error 0500 if let hresponse = task.response as? NSHTTPURLResponse { 0501 resp.headers = hresponse.allHeaderFields as? Dictionary<String,String> 0502 resp.mimeType = hresponse.MIMEType 0503 resp.suggestedFilename = hresponse.suggestedFilename 0504 resp.statusCode = hresponse.statusCode 0505 resp.URL = hresponse.URL 0506 } 0507 if let code = resp.statusCode where resp.statusCode > 299 { 0508 resp.error = createError(code) 0509 } 0510 if let handler = resp.completionHandler { 0511 handler(resp) 0512 } 0513 removeTask(task) 0514 } 0515 0516 //handle authenication 0517 func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { 0518 var sec = security 0519 var au = auth 0520 if let resp = responseForTask(task) { 0521 if let s = resp.security { 0522 sec = s 0523 } 0524 if let a = resp.auth { 0525 au = a 0526 } 0527 } 0528 if let sec = sec where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 0529 let space = challenge.protectionSpace 0530 if let trust = space.serverTrust { 0531 if sec.isValid(trust, domain: space.host) { 0532 completionHandler(.UseCredential, NSURLCredential(trust: trust)) 0533 return 0534 } 0535 } 0536 completionHandler(.CancelAuthenticationChallenge, nil) 0537 return 0538 0539 } else if let a = au { 0540 let cred = a(challenge) 0541 if let c = cred { 0542 completionHandler(.UseCredential, c) 0543 return 0544 } 0545 completionHandler(.RejectProtectionSpace, nil) 0546 return 0547 } 0548 completionHandler(.PerformDefaultHandling, nil) 0549 } 0550 //upload progress 0551 func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { 0552 guard let resp = responseForTask(task) else { return } 0553 progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent) 0554 } 0555 //download progress 0556 func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 0557 guard let resp = responseForTask(downloadTask) else { return } 0558 progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: bytesWritten) 0559 } 0560 0561 //handle progress 0562 func progressHandler
Operation.swift:135 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:131 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:147 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:143 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:159 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }Operation.swift:155 guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }Operation.swift:464 if let resp = responseForTask(task) {Operation.swift:488 guard let resp = responseForTask(dataTask) else { return }Operation.swift:498 guard let resp = responseForTask(task) else { return }Operation.swift:520 if let resp = responseForTask(task) {Operation.swift:552 guard let resp = responseForTask(task) else { return }Operation.swift:557 guard let resp = responseForTask(downloadTask) else { return }(response: Response, expectedLength: Int64, currentLength: Int64) { 0563 guard let handler = response.progressHandler else { return } 0564 let slice = Float(1.0)/Float(expectedLength) 0565 handler(slice*Float(currentLength)) 0566 } 0567 0568 /** 0569 Create an error for response you probably don't want (400-500 HTTP responses for example). 0570 0571 -parameter code: Code for error. 0572 0573 -returns An NSError. 0574 */ 0575 private func createError
Operation.swift:492 progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length))Operation.swift:553 progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent)Operation.swift:558 progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: bytesWritten)(code: Int) -> NSError { 0576 let text = HTTPStatusCode(statusCode: code).statusDescription 0577 return NSError(domain: "HTTP", code: code, userInfo: [NSLocalizedDescriptionKey: text]) 0578 } 0579 } 0580 0581 /** 0582 Handles providing singletons of NSURLSession. 0583 */ 0584 class SharedSession
Operation.swift:508 resp.error = createError(code){ 0585 static let defaultSession
Operation.swift:243 public init(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) {= NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), 0586 delegate: DelegateManager.sharedInstance, delegateQueue: nil) 0587 static let ephemeralSession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), 0588 delegate: DelegateManager.sharedInstance, delegateQueue: nil) 0589 }
Operation.swift:243 public init(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) {