0001 // Manager.swift 0002 // 0003 // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) 0004 // 0005 // Permission is hereby granted, free of charge, to any person obtaining a copy 0006 // of this software and associated documentation files (the "Software"), to deal 0007 // in the Software without restriction, including without limitation the rights 0008 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 0009 // copies of the Software, and to permit persons to whom the Software is 0010 // furnished to do so, subject to the following conditions: 0011 // 0012 // The above copyright notice and this permission notice shall be included in 0013 // all copies or substantial portions of the Software. 0014 // 0015 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 0016 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 0017 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 0018 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 0019 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 0020 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 0021 // THE SOFTWARE. 0022 0023 import Foundation 0024 0025 /** 0026 Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. 0027 */ 0028 public class Manager{ 0029 0030 // MARK: - Properties 0031 0032 /** 0033 A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly 0034 for any ad hoc requests. 0035 */ 0036 public static let sharedInstance
Alamofire.swift:126 return Manager.sharedInstance.request(Alamofire.swift:145 return Manager.sharedInstance.request(URLRequest.URLRequest)Alamofire.swift:169 return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)Alamofire.swift:181 return Manager.sharedInstance.upload(URLRequest, file: file)Alamofire.swift:203 return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)Alamofire.swift:215 return Manager.sharedInstance.upload(URLRequest, data: data)Alamofire.swift:237 return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)Alamofire.swift:249 return Manager.sharedInstance.upload(URLRequest, stream: stream)Alamofire.swift:270 encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,Alamofire.swift:271 encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)Alamofire.swift:273 return Manager.sharedInstance.upload(Alamofire.swift:295 encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,Alamofire.swift:296 encodingCompletion: (Manager.MultipartFormDataEncodingResult -> Void)?)Alamofire.swift:298 return Manager.sharedInstance.upload(Alamofire.swift:331 return Manager.sharedInstance.download(Alamofire.swift:350 return Manager.sharedInstance.download(URLRequest, destination: destination)Alamofire.swift:367 return Manager.sharedInstance.download(data, destination: destination)Download.swift:25 extension Manager {Manager.swift:36 public static let sharedInstance: Manager = {Manager.swift:38 configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeadersManager.swift:40 return Manager(configuration: configuration)Stream.swift:28 extension Manager {Stream.swift:86 extension Manager.SessionDelegate: NSURLSessionStreamDelegate {Upload.swift:25 extension Manager {Upload.swift:239 encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,Upload.swift:279 encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,: Manager = { 0037 let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 0038 configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders 0039 0040 return Manager(configuration: configuration) 0041 }() 0042 0043 /** 0044 Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. 0045 */ 0046 public static let defaultHTTPHeaders
Alamofire.swift:126 return Manager.sharedInstance.request(Alamofire.swift:145 return Manager.sharedInstance.request(URLRequest.URLRequest)Alamofire.swift:169 return Manager.sharedInstance.upload(method, URLString, headers: headers, file: file)Alamofire.swift:181 return Manager.sharedInstance.upload(URLRequest, file: file)Alamofire.swift:203 return Manager.sharedInstance.upload(method, URLString, headers: headers, data: data)Alamofire.swift:215 return Manager.sharedInstance.upload(URLRequest, data: data)Alamofire.swift:237 return Manager.sharedInstance.upload(method, URLString, headers: headers, stream: stream)Alamofire.swift:249 return Manager.sharedInstance.upload(URLRequest, stream: stream)Alamofire.swift:273 return Manager.sharedInstance.upload(Alamofire.swift:298 return Manager.sharedInstance.upload(Alamofire.swift:331 return Manager.sharedInstance.download(Alamofire.swift:350 return Manager.sharedInstance.download(URLRequest, destination: destination)Alamofire.swift:367 return Manager.sharedInstance.download(data, destination: destination): [String: String] = { 0047 // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 0048 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" 0049 0050 // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 0051 let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in 0052 let quality = 1.0 - (Double(index) * 0.1) 0053 return "\(languageCode);q=\(quality)" 0054 }.joinWithSeparator(", ") 0055 0056 // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 0057 let userAgent: String = { 0058 if let info = NSBundle.mainBundle().infoDictionary { 0059 let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown" 0060 let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown" 0061 let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown" 0062 let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" 0063 0064 var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString 0065 let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString 0066 0067 if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) { 0068 return mutableUserAgent as String 0069 } 0070 } 0071 0072 return "Alamofire" 0073 }() 0074 0075 return [ 0076 "Accept-Encoding": acceptEncoding, 0077 "Accept-Language": acceptLanguage, 0078 "User-Agent": userAgent 0079 ] 0080 }() 0081 0082 let queue
Manager.swift:38 configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders= dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) 0083 0084 /// The underlying session. 0085 public let session
Download.swift:36 dispatch_sync(queue) {Download.swift:40 dispatch_sync(queue) {Manager.swift:204 dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }Stream.swift:39 dispatch_sync(queue) {Stream.swift:43 dispatch_sync(queue) {Upload.swift:38 dispatch_sync(queue) {Upload.swift:42 dispatch_sync(queue) {Upload.swift:46 dispatch_sync(queue) {: NSURLSession 0086 0087 /// The session delegate handling all the task and session delegate callbacks. 0088 public let delegate
Download.swift:37 downloadTask = self.session.downloadTaskWithRequest(request)Download.swift:41 downloadTask = self.session.downloadTaskWithResumeData(resumeData)Download.swift:45 let request = Request(session: session, task: downloadTask)Manager.swift:126 self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)Manager.swift:147 self.session = sessionManager.swift:155 session.serverTrustPolicyManager = serverTrustPolicyManagerManager.swift:164 session.invalidateAndCancel()Manager.swift:204 dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }Manager.swift:206 let request = Request(session: session, task: dataTask)Stream.swift:40 streamTask = self.session.streamTaskWithHostName(hostName, port: port)Stream.swift:44 streamTask = self.session.streamTaskWithNetService(netService)Stream.swift:48 let request = Request(session: session, task: streamTask)Upload.swift:39 uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)Upload.swift:43 uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)Upload.swift:47 uploadTask = self.session.uploadTaskWithStreamedRequest(request)Upload.swift:53 let request = Request(session: session, task: uploadTask)Upload.swift:289 let isBackgroundSession = self.session.configuration.identifier != nil: SessionDelegate 0089 0090 /// Whether to start requests immediately after being constructed. `true` by default. 0091 public var startRequestsImmediately
Download.swift:53 delegate[request.delegate.task] = request.delegateManager.swift:125 self.delegate = delegateManager.swift:146 self.delegate = delegateManager.swift:157 delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session inManager.swift:207 delegate[request.delegate.task] = request.delegateStream.swift:50 delegate[request.delegate.task] = request.delegateUpload.swift:61 delegate[request.delegate.task] = request.delegate: Bool = true 0092 0093 /** 0094 The background completion handler closure provided by the UIApplicationDelegate 0095 `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background 0096 completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation 0097 will automatically call the handler. 0098 0099 If you need to handle your own events before the handler is called, then you need to override the 0100 SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. 0101 0102 `nil` by default. 0103 */ 0104 public var backgroundCompletionHandler
Download.swift:55 if startRequestsImmediately {Manager.swift:209 if startRequestsImmediately {Stream.swift:52 if startRequestsImmediately {Upload.swift:63 if startRequestsImmediately {: (() -> Void)? 0105 0106 // MARK: - Lifecycle 0107 0108 /** 0109 Initializes the `Manager` instance with the specified configuration, delegate and server trust policy. 0110 0111 - parameter configuration: The configuration used to construct the managed session. 0112 `NSURLSessionConfiguration.defaultSessionConfiguration()` by default. 0113 - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by 0114 default. 0115 - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust 0116 challenges. `nil` by default. 0117 0118 - returns: The new `Manager` instance. 0119 */ 0120 public init
Manager.swift:159 dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }( 0121 configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), 0122 delegate: SessionDelegate = SessionDelegate(), 0123 serverTrustPolicyManager: ServerTrustPolicyManager? = nil) 0124 { 0125 self.delegate = delegate 0126 self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) 0127 0128 commonInit(serverTrustPolicyManager: serverTrustPolicyManager) 0129 } 0130 0131 /** 0132 Initializes the `Manager` instance with the specified session, delegate and server trust policy. 0133 0134 - parameter session: The URL session. 0135 - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. 0136 - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust 0137 challenges. `nil` by default. 0138 0139 - returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter. 0140 */ 0141 public init?( 0142 session: NSURLSession, 0143 delegate: SessionDelegate, 0144 serverTrustPolicyManager: ServerTrustPolicyManager? = nil) 0145 { 0146 self.delegate = delegate 0147 self.session = session 0148 0149 guard delegate === session.delegate else { return nil } 0150 0151 commonInit(serverTrustPolicyManager: serverTrustPolicyManager) 0152 } 0153 0154 private func commonInit
Manager.swift:40 return Manager(configuration: configuration)(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) { 0155 session.serverTrustPolicyManager = serverTrustPolicyManager 0156 0157 delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in 0158 guard let strongSelf = self else { return } 0159 dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() } 0160 } 0161 } 0162 0163 deinit { 0164 session.invalidateAndCancel() 0165 } 0166 0167 // MARK: - Request 0168 0169 /** 0170 Creates a request for the specified method, URL string, parameters, parameter encoding and headers. 0171 0172 - parameter method: The HTTP method. 0173 - parameter URLString: The URL string. 0174 - parameter parameters: The parameters. `nil` by default. 0175 - parameter encoding: The parameter encoding. `.URL` by default. 0176 - parameter headers: The HTTP headers. `nil` by default. 0177 0178 - returns: The created request. 0179 */ 0180 public func request
Manager.swift:128 commonInit(serverTrustPolicyManager: serverTrustPolicyManager)Manager.swift:151 commonInit(serverTrustPolicyManager: serverTrustPolicyManager)( 0181 method: Method, 0182 _ URLString: URLStringConvertible, 0183 parameters: [String: AnyObject]? = nil, 0184 encoding: ParameterEncoding = .URL, 0185 headers: [String: String]? = nil) 0186 -> Request 0187 { 0188 let mutableURLRequest = URLRequest(method, URLString, headers: headers) 0189 let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 0190 return request(encodedURLRequest) 0191 } 0192 0193 /** 0194 Creates a request for the specified URL request. 0195 0196 If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. 0197 0198 - parameter URLRequest: The URL request 0199 0200 - returns: The created request. 0201 */ 0202 public func request
Alamofire.swift:126 return Manager.sharedInstance.request((URLRequest: URLRequestConvertible) -> Request { 0203 var dataTask: NSURLSessionDataTask! 0204 dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } 0205 0206 let request = Request(session: session, task: dataTask) 0207 delegate[request.delegate.task] = request.delegate 0208 0209 if startRequestsImmediately { 0210 request.resume() 0211 } 0212 0213 return request 0214 } 0215 0216 // MARK: - SessionDelegate 0217 0218 /** 0219 Responsible for handling all delegate callbacks for the underlying session. 0220 */ 0221 public final class SessionDelegate
Alamofire.swift:145 return Manager.sharedInstance.request(URLRequest.URLRequest)Manager.swift:190 return request(encodedURLRequest): NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { 0222 private var subdelegates
Manager.swift:88 public let delegate: SessionDelegateManager.swift:122 delegate: SessionDelegate = SessionDelegate(),Manager.swift:122 delegate: SessionDelegate = SessionDelegate(),Manager.swift:143 delegate: SessionDelegate,Stream.swift:86 extension Manager.SessionDelegate: NSURLSessionStreamDelegate {: [Int: Request.TaskDelegate] = [:] 0223 private let subdelegateQueue
Manager.swift:228 dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }Manager.swift:234 dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }= dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) 0224 0225 subscript
Manager.swift:228 dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }Manager.swift:234 dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }(task: NSURLSessionTask) -> Request.TaskDelegate? { 0226 get { 0227 var subdelegate: Request.TaskDelegate? 0228 dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } 0229 0230 return subdelegate 0231 } 0232 0233 set { 0234 dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } 0235 } 0236 } 0237 0238 /** 0239 Initializes the `SessionDelegate` instance. 0240 0241 - returns: The new `SessionDelegate` instance. 0242 */ 0243 public override init
Download.swift:53 delegate[request.delegate.task] = request.delegateManager.swift:207 delegate[request.delegate.task] = request.delegateManager.swift:381 } else if let delegate = self[task] {Manager.swift:407 } else if let delegate = self[task] {Manager.swift:430 } else if let delegate = self[task] as? Request.UploadTaskDelegate {Manager.swift:451 } else if let delegate = self[task] {Manager.swift:457 self[task] = nilManager.swift:519 self[downloadTask] = downloadDelegateManager.swift:533 } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {Manager.swift:559 } else if let delegate = self[dataTask] as? Request.DataTaskDelegate {Manager.swift:602 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {Manager.swift:628 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {Manager.swift:659 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {Stream.swift:50 delegate[request.delegate.task] = request.delegateUpload.swift:61 delegate[request.delegate.task] = request.delegate() { 0244 super.init() 0245 } 0246 0247 // MARK: - NSURLSessionDelegate 0248 0249 // MARK: Override Closures 0250 0251 /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`. 0252 public var sessionDidBecomeInvalidWithError
Manager.swift:122 delegate: SessionDelegate = SessionDelegate(),: ((NSURLSession, NSError?) -> Void)? 0253 0254 /// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`. 0255 public var sessionDidReceiveChallenge
Manager.swift:269 sessionDidBecomeInvalidWithError?(session, error)Manager.swift:681 return sessionDidBecomeInvalidWithError != nil: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? 0256 0257 /// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`. 0258 public var sessionDidFinishEventsForBackgroundURLSession
Manager.swift:287 if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {Manager.swift:683 return sessionDidReceiveChallenge != nil: ((NSURLSession) -> Void)? 0259 0260 // MARK: Delegate Methods 0261 0262 /** 0263 Tells the delegate that the session has been invalidated. 0264 0265 - parameter session: The session object that was invalidated. 0266 - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. 0267 */ 0268 public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { 0269 sessionDidBecomeInvalidWithError?(session, error) 0270 } 0271 0272 /** 0273 Requests credentials from the delegate in response to a session-level authentication request from the remote server. 0274 0275 - parameter session: The session containing the task that requested authentication. 0276 - parameter challenge: An object that contains the request for authentication. 0277 - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. 0278 */ 0279 public func URLSession
Manager.swift:157 delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session inManager.swift:314 sessionDidFinishEventsForBackgroundURLSession?(session)Manager.swift:685 return sessionDidFinishEventsForBackgroundURLSession != nil( 0280 session: NSURLSession, 0281 didReceiveChallenge challenge: NSURLAuthenticationChallenge, 0282 completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) 0283 { 0284 var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling 0285 var credential: NSURLCredential? 0286 0287 if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { 0288 (disposition, credential) = sessionDidReceiveChallenge(session, challenge) 0289 } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 0290 let host = challenge.protectionSpace.host 0291 0292 if let 0293 serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), 0294 serverTrust = challenge.protectionSpace.serverTrust 0295 { 0296 if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { 0297 disposition = .UseCredential 0298 credential = NSURLCredential(forTrust: serverTrust) 0299 } else { 0300 disposition = .CancelAuthenticationChallenge 0301 } 0302 } 0303 } 0304 0305 completionHandler(disposition, credential) 0306 } 0307 0308 /** 0309 Tells the delegate that all messages enqueued for a session have been delivered. 0310 0311 - parameter session: The session that no longer has any outstanding requests. 0312 */ 0313 public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { 0314 sessionDidFinishEventsForBackgroundURLSession?(session) 0315 } 0316 0317 // MARK: - NSURLSessionTaskDelegate 0318 0319 // MARK: Override Closures 0320 0321 /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. 0322 public var taskWillPerformHTTPRedirection
Manager.swift:389 URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler): ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? 0323 0324 /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. 0325 public var taskDidReceiveChallenge
Manager.swift:358 if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {Manager.swift:687 return taskWillPerformHTTPRedirection != nil: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))? 0326 0327 /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. 0328 public var taskNeedNewBodyStream
Manager.swift:379 if let taskDidReceiveChallenge = taskDidReceiveChallenge {: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? 0329 0330 /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. 0331 public var taskDidSendBodyData
Manager.swift:405 if let taskNeedNewBodyStream = taskNeedNewBodyStream {: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? 0332 0333 /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. 0334 public var taskDidComplete
Manager.swift:428 if let taskDidSendBodyData = taskDidSendBodyData {: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? 0335 0336 // MARK: Delegate Methods 0337 0338 /** 0339 Tells the delegate that the remote server requested an HTTP redirect. 0340 0341 - parameter session: The session containing the task whose request resulted in a redirect. 0342 - parameter task: The task whose request resulted in a redirect. 0343 - parameter response: An object containing the server’s response to the original request. 0344 - parameter request: A URL request object filled out with the new location. 0345 - parameter completionHandler: A closure that your handler should call with either the value of the request 0346 parameter, a modified URL request object, or NULL to refuse the redirect and 0347 return the body of the redirect response. 0348 */ 0349 public func URLSession( 0350 session: NSURLSession, 0351 task: NSURLSessionTask, 0352 willPerformHTTPRedirection response: NSHTTPURLResponse, 0353 newRequest request: NSURLRequest, 0354 completionHandler: ((NSURLRequest?) -> Void)) 0355 { 0356 var redirectRequest: NSURLRequest? = request 0357 0358 if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { 0359 redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) 0360 } 0361 0362 completionHandler(redirectRequest) 0363 } 0364 0365 /** 0366 Requests credentials from the delegate in response to an authentication request from the remote server. 0367 0368 - parameter session: The session containing the task whose request requires authentication. 0369 - parameter task: The task whose request requires authentication. 0370 - parameter challenge: An object that contains the request for authentication. 0371 - parameter completionHandler: A handler that your delegate method must call providing the disposition and credential. 0372 */ 0373 public func URLSession( 0374 session: NSURLSession, 0375 task: NSURLSessionTask, 0376 didReceiveChallenge challenge: NSURLAuthenticationChallenge, 0377 completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) 0378 { 0379 if let taskDidReceiveChallenge = taskDidReceiveChallenge { 0380 completionHandler(taskDidReceiveChallenge(session, task, challenge)) 0381 } else if let delegate = self[task] { 0382 delegate.URLSession( 0383 session, 0384 task: task, 0385 didReceiveChallenge: challenge, 0386 completionHandler: completionHandler 0387 ) 0388 } else { 0389 URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) 0390 } 0391 } 0392 0393 /** 0394 Tells the delegate when a task requires a new request body stream to send to the remote server. 0395 0396 - parameter session: The session containing the task that needs a new body stream. 0397 - parameter task: The task that needs a new body stream. 0398 - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. 0399 */ 0400 public func URLSession( 0401 session: NSURLSession, 0402 task: NSURLSessionTask, 0403 needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) 0404 { 0405 if let taskNeedNewBodyStream = taskNeedNewBodyStream { 0406 completionHandler(taskNeedNewBodyStream(session, task)) 0407 } else if let delegate = self[task] { 0408 delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) 0409 } 0410 } 0411 0412 /** 0413 Periodically informs the delegate of the progress of sending body content to the server. 0414 0415 - parameter session: The session containing the data task. 0416 - parameter task: The data task. 0417 - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. 0418 - parameter totalBytesSent: The total number of bytes sent so far. 0419 - parameter totalBytesExpectedToSend: The expected length of the body data. 0420 */ 0421 public func URLSession( 0422 session: NSURLSession, 0423 task: NSURLSessionTask, 0424 didSendBodyData bytesSent: Int64, 0425 totalBytesSent: Int64, 0426 totalBytesExpectedToSend: Int64) 0427 { 0428 if let taskDidSendBodyData = taskDidSendBodyData { 0429 taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) 0430 } else if let delegate = self[task] as? Request.UploadTaskDelegate { 0431 delegate.URLSession( 0432 session, 0433 task: task, 0434 didSendBodyData: bytesSent, 0435 totalBytesSent: totalBytesSent, 0436 totalBytesExpectedToSend: totalBytesExpectedToSend 0437 ) 0438 } 0439 } 0440 0441 /** 0442 Tells the delegate that the task finished transferring data. 0443 0444 - parameter session: The session containing the task whose request finished transferring data. 0445 - parameter task: The task whose request finished transferring data. 0446 - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. 0447 */ 0448 public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { 0449 if let taskDidComplete = taskDidComplete { 0450 taskDidComplete(session, task, error) 0451 } else if let delegate = self[task] { 0452 delegate.URLSession(session, task: task, didCompleteWithError: error) 0453 } 0454 0455 NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task) 0456 0457 self[task] = nil 0458 } 0459 0460 // MARK: - NSURLSessionDataDelegate 0461 0462 // MARK: Override Closures 0463 0464 /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. 0465 public var dataTaskDidReceiveResponse
Manager.swift:449 if let taskDidComplete = taskDidComplete {: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? 0466 0467 /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. 0468 public var dataTaskDidBecomeDownloadTask
Manager.swift:496 if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {Manager.swift:689 return dataTaskDidReceiveResponse != nil: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? 0469 0470 /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. 0471 public var dataTaskDidReceiveData
Manager.swift:515 if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? 0472 0473 /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. 0474 public var dataTaskWillCacheResponse
Manager.swift:531 if let dataTaskDidReceiveData = dataTaskDidReceiveData {: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? 0475 0476 // MARK: Delegate Methods 0477 0478 /** 0479 Tells the delegate that the data task received the initial reply (headers) from the server. 0480 0481 - parameter session: The session containing the data task that received an initial reply. 0482 - parameter dataTask: The data task that received an initial reply. 0483 - parameter response: A URL response object populated with headers. 0484 - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a 0485 constant to indicate whether the transfer should continue as a data task or 0486 should become a download task. 0487 */ 0488 public func URLSession( 0489 session: NSURLSession, 0490 dataTask: NSURLSessionDataTask, 0491 didReceiveResponse response: NSURLResponse, 0492 completionHandler: ((NSURLSessionResponseDisposition) -> Void)) 0493 { 0494 var disposition: NSURLSessionResponseDisposition = .Allow 0495 0496 if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { 0497 disposition = dataTaskDidReceiveResponse(session, dataTask, response) 0498 } 0499 0500 completionHandler(disposition) 0501 } 0502 0503 /** 0504 Tells the delegate that the data task was changed to a download task. 0505 0506 - parameter session: The session containing the task that was replaced by a download task. 0507 - parameter dataTask: The data task that was replaced by a download task. 0508 - parameter downloadTask: The new download task that replaced the data task. 0509 */ 0510 public func URLSession( 0511 session: NSURLSession, 0512 dataTask: NSURLSessionDataTask, 0513 didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) 0514 { 0515 if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { 0516 dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) 0517 } else { 0518 let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) 0519 self[downloadTask] = downloadDelegate 0520 } 0521 } 0522 0523 /** 0524 Tells the delegate that the data task has received some of the expected data. 0525 0526 - parameter session: The session containing the data task that provided data. 0527 - parameter dataTask: The data task that provided data. 0528 - parameter data: A data object containing the transferred data. 0529 */ 0530 public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { 0531 if let dataTaskDidReceiveData = dataTaskDidReceiveData { 0532 dataTaskDidReceiveData(session, dataTask, data) 0533 } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { 0534 delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) 0535 } 0536 } 0537 0538 /** 0539 Asks the delegate whether the data (or upload) task should store the response in the cache. 0540 0541 - parameter session: The session containing the data (or upload) task. 0542 - parameter dataTask: The data (or upload) task. 0543 - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current 0544 caching policy and the values of certain received headers, such as the Pragma 0545 and Cache-Control headers. 0546 - parameter completionHandler: A block that your handler must call, providing either the original proposed 0547 response, a modified version of that response, or NULL to prevent caching the 0548 response. If your delegate implements this method, it must call this completion 0549 handler; otherwise, your app leaks memory. 0550 */ 0551 public func URLSession( 0552 session: NSURLSession, 0553 dataTask: NSURLSessionDataTask, 0554 willCacheResponse proposedResponse: NSCachedURLResponse, 0555 completionHandler: ((NSCachedURLResponse?) -> Void)) 0556 { 0557 if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { 0558 completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) 0559 } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { 0560 delegate.URLSession( 0561 session, 0562 dataTask: dataTask, 0563 willCacheResponse: proposedResponse, 0564 completionHandler: completionHandler 0565 ) 0566 } else { 0567 completionHandler(proposedResponse) 0568 } 0569 } 0570 0571 // MARK: - NSURLSessionDownloadDelegate 0572 0573 // MARK: Override Closures 0574 0575 /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. 0576 public var downloadTaskDidFinishDownloadingToURL
Manager.swift:557 if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? 0577 0578 /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. 0579 public var downloadTaskDidWriteData
Manager.swift:600 if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? 0580 0581 /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. 0582 public var downloadTaskDidResumeAtOffset
Manager.swift:626 if let downloadTaskDidWriteData = downloadTaskDidWriteData {: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? 0583 0584 // MARK: Delegate Methods 0585 0586 /** 0587 Tells the delegate that a download task has finished downloading. 0588 0589 - parameter session: The session containing the download task that finished. 0590 - parameter downloadTask: The download task that finished. 0591 - parameter location: A file URL for the temporary file. Because the file is temporary, you must either 0592 open the file for reading or move it to a permanent location in your app’s sandbox 0593 container directory before returning from this delegate method. 0594 */ 0595 public func URLSession( 0596 session: NSURLSession, 0597 downloadTask: NSURLSessionDownloadTask, 0598 didFinishDownloadingToURL location: NSURL) 0599 { 0600 if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { 0601 downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) 0602 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { 0603 delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) 0604 } 0605 } 0606 0607 /** 0608 Periodically informs the delegate about the download’s progress. 0609 0610 - parameter session: The session containing the download task. 0611 - parameter downloadTask: The download task. 0612 - parameter bytesWritten: The number of bytes transferred since the last time this delegate 0613 method was called. 0614 - parameter totalBytesWritten: The total number of bytes transferred so far. 0615 - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length 0616 header. If this header was not provided, the value is 0617 `NSURLSessionTransferSizeUnknown`. 0618 */ 0619 public func URLSession( 0620 session: NSURLSession, 0621 downloadTask: NSURLSessionDownloadTask, 0622 didWriteData bytesWritten: Int64, 0623 totalBytesWritten: Int64, 0624 totalBytesExpectedToWrite: Int64) 0625 { 0626 if let downloadTaskDidWriteData = downloadTaskDidWriteData { 0627 downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) 0628 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { 0629 delegate.URLSession( 0630 session, 0631 downloadTask: downloadTask, 0632 didWriteData: bytesWritten, 0633 totalBytesWritten: totalBytesWritten, 0634 totalBytesExpectedToWrite: totalBytesExpectedToWrite 0635 ) 0636 } 0637 } 0638 0639 /** 0640 Tells the delegate that the download task has resumed downloading. 0641 0642 - parameter session: The session containing the download task that finished. 0643 - parameter downloadTask: The download task that resumed. See explanation in the discussion. 0644 - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the 0645 existing content, then this value is zero. Otherwise, this value is an 0646 integer representing the number of bytes on disk that do not need to be 0647 retrieved again. 0648 - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. 0649 If this header was not provided, the value is NSURLSessionTransferSizeUnknown. 0650 */ 0651 public func URLSession( 0652 session: NSURLSession, 0653 downloadTask: NSURLSessionDownloadTask, 0654 didResumeAtOffset fileOffset: Int64, 0655 expectedTotalBytes: Int64) 0656 { 0657 if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { 0658 downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) 0659 } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { 0660 delegate.URLSession( 0661 session, 0662 downloadTask: downloadTask, 0663 didResumeAtOffset: fileOffset, 0664 expectedTotalBytes: expectedTotalBytes 0665 ) 0666 } 0667 } 0668 0669 // MARK: - NSURLSessionStreamDelegate 0670 0671 var _streamTaskReadClosed
Manager.swift:657 if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {: Any? 0672 var _streamTaskWriteClosed
Stream.swift:93 return _streamTaskReadClosed as? (NSURLSession, NSURLSessionStreamTask) -> VoidStream.swift:96 _streamTaskReadClosed = newValue: Any? 0673 var _streamTaskBetterRouteDiscovered
Stream.swift:103 return _streamTaskWriteClosed as? (NSURLSession, NSURLSessionStreamTask) -> VoidStream.swift:106 _streamTaskWriteClosed = newValue: Any? 0674 var _streamTaskDidBecomeInputStream
Stream.swift:113 return _streamTaskBetterRouteDiscovered as? (NSURLSession, NSURLSessionStreamTask) -> VoidStream.swift:116 _streamTaskBetterRouteDiscovered = newValue: Any? 0675 0676 // MARK: - NSObject 0677 0678 public override func respondsToSelector(selector: Selector) -> Bool { 0679 switch selector { 0680 case "URLSession:didBecomeInvalidWithError:": 0681 return sessionDidBecomeInvalidWithError != nil 0682 case "URLSession:didReceiveChallenge:completionHandler:": 0683 return sessionDidReceiveChallenge != nil 0684 case "URLSessionDidFinishEventsForBackgroundURLSession:": 0685 return sessionDidFinishEventsForBackgroundURLSession != nil 0686 case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:": 0687 return taskWillPerformHTTPRedirection != nil 0688 case "URLSession:dataTask:didReceiveResponse:completionHandler:": 0689 return dataTaskDidReceiveResponse != nil 0690 default: 0691 return self.dynamicType.instancesRespondToSelector(selector) 0692 } 0693 } 0694 } 0695 } 0696
Stream.swift:123 return _streamTaskDidBecomeInputStream as? (NSURLSession, NSURLSessionStreamTask, NSInputStream, NSOutputStream) -> VoidStream.swift:126 _streamTaskDidBecomeInputStream = newValue