Alamofire.swift 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. /// Alamofire errors
  24. public let AlamofireErrorDomain = "com.alamofire.error"
  25. // MARK: - URLStringConvertible
  26. /**
  27. Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
  28. */
  29. public protocol URLStringConvertible {
  30. /**
  31. A URL that conforms to RFC 2396.
  32. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
  33. See http://tools.ietf.org/html/rfc2396
  34. See http://tools.ietf.org/html/rfc1738
  35. See http://tools.ietf.org/html/rfc1808
  36. */
  37. var URLString: String { get }
  38. }
  39. extension String: URLStringConvertible {
  40. public var URLString: String {
  41. return self
  42. }
  43. }
  44. extension NSURL: URLStringConvertible {
  45. public var URLString: String {
  46. return absoluteString!
  47. }
  48. }
  49. extension NSURLComponents: URLStringConvertible {
  50. public var URLString: String {
  51. return URL!.URLString
  52. }
  53. }
  54. extension NSURLRequest: URLStringConvertible {
  55. public var URLString: String {
  56. return URL!.URLString
  57. }
  58. }
  59. // MARK: - URLRequestConvertible
  60. /**
  61. Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
  62. */
  63. public protocol URLRequestConvertible {
  64. /// The URL request.
  65. var URLRequest: NSURLRequest { get }
  66. }
  67. extension NSURLRequest: URLRequestConvertible {
  68. public var URLRequest: NSURLRequest {
  69. return self
  70. }
  71. }
  72. // MARK: -
  73. /**
  74. Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
  75. */
  76. public class Request {
  77. let delegate: TaskDelegate
  78. /// The underlying task.
  79. public var task: NSURLSessionTask { return delegate.task }
  80. /// The session belonging to the underlying task.
  81. public let session: NSURLSession
  82. /// The request sent or to be sent to the server.
  83. public var request: NSURLRequest { return task.originalRequest }
  84. /// The response received from the server, if any.
  85. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
  86. /// The progress of the request lifecycle.
  87. public var progress: NSProgress { return delegate.progress }
  88. init(session: NSURLSession, task: NSURLSessionTask) {
  89. self.session = session
  90. switch task {
  91. case is NSURLSessionUploadTask:
  92. self.delegate = UploadTaskDelegate(task: task)
  93. case is NSURLSessionDataTask:
  94. self.delegate = DataTaskDelegate(task: task)
  95. case is NSURLSessionDownloadTask:
  96. self.delegate = DownloadTaskDelegate(task: task)
  97. default:
  98. self.delegate = TaskDelegate(task: task)
  99. }
  100. }
  101. // MARK: Authentication
  102. /**
  103. Associates an HTTP Basic credential with the request.
  104. :param: user The user.
  105. :param: password The password.
  106. :returns: The request.
  107. */
  108. public func authenticate(#user: String, password: String) -> Self {
  109. let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
  110. return authenticate(usingCredential: credential)
  111. }
  112. /**
  113. Associates a specified credential with the request.
  114. :param: credential The credential.
  115. :returns: The request.
  116. */
  117. public func authenticate(usingCredential credential: NSURLCredential) -> Self {
  118. delegate.credential = credential
  119. return self
  120. }
  121. // MARK: Progress
  122. /**
  123. Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
  124. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
  125. - For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
  126. :param: closure The code to be executed periodically during the lifecycle of the request.
  127. :returns: The request.
  128. */
  129. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  130. if let uploadDelegate = delegate as? UploadTaskDelegate {
  131. uploadDelegate.uploadProgress = closure
  132. } else if let dataDelegate = delegate as? DataTaskDelegate {
  133. dataDelegate.dataProgress = closure
  134. } else if let downloadDelegate = delegate as? DownloadTaskDelegate {
  135. downloadDelegate.downloadProgress = closure
  136. }
  137. return self
  138. }
  139. // MARK: Response
  140. /**
  141. A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
  142. */
  143. public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
  144. /**
  145. Creates a response serializer that returns the associated data as-is.
  146. :returns: A data response serializer.
  147. */
  148. public class func responseDataSerializer() -> Serializer {
  149. return { (request, response, data) in
  150. return (data, nil)
  151. }
  152. }
  153. /**
  154. Adds a handler to be called once the request has finished.
  155. :param: completionHandler The code to be executed once the request has finished.
  156. :returns: The request.
  157. */
  158. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  159. return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler)
  160. }
  161. /**
  162. Adds a handler to be called once the request has finished.
  163. :param: queue The queue on which the completion handler is dispatched.
  164. :param: serializer The closure responsible for serializing the request, response, and data.
  165. :param: completionHandler The code to be executed once the request has finished.
  166. :returns: The request.
  167. */
  168. public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  169. delegate.queue.addOperationWithBlock {
  170. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
  171. dispatch_async(queue ?? dispatch_get_main_queue()) {
  172. completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
  173. }
  174. }
  175. return self
  176. }
  177. /**
  178. Suspends the request.
  179. */
  180. public func suspend() {
  181. task.suspend()
  182. }
  183. /**
  184. Resumes the request.
  185. */
  186. public func resume() {
  187. task.resume()
  188. }
  189. /**
  190. Cancels the request.
  191. */
  192. public func cancel() {
  193. if let downloadDelegate = delegate as? DownloadTaskDelegate {
  194. downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
  195. downloadDelegate.resumeData = data
  196. }
  197. } else {
  198. task.cancel()
  199. }
  200. }
  201. class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
  202. let task: NSURLSessionTask
  203. let queue: NSOperationQueue
  204. let progress: NSProgress
  205. var data: NSData? { return nil }
  206. private(set) var error: NSError?
  207. var credential: NSURLCredential?
  208. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  209. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  210. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  211. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  212. init(task: NSURLSessionTask) {
  213. self.task = task
  214. self.progress = NSProgress(totalUnitCount: 0)
  215. self.queue = {
  216. let operationQueue = NSOperationQueue()
  217. operationQueue.maxConcurrentOperationCount = 1
  218. operationQueue.qualityOfService = NSQualityOfService.Utility
  219. operationQueue.suspended = true
  220. return operationQueue
  221. }()
  222. }
  223. deinit {
  224. queue.cancelAllOperations()
  225. queue.suspended = true
  226. }
  227. // MARK: NSURLSessionTaskDelegate
  228. func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
  229. var redirectRequest = request
  230. if taskWillPerformHTTPRedirection != nil {
  231. redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
  232. }
  233. completionHandler(redirectRequest)
  234. }
  235. func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
  236. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  237. var credential: NSURLCredential?
  238. if taskDidReceiveChallenge != nil {
  239. (disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
  240. } else {
  241. if challenge.previousFailureCount > 0 {
  242. disposition = .CancelAuthenticationChallenge
  243. } else {
  244. credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  245. if credential != nil {
  246. disposition = .UseCredential
  247. }
  248. }
  249. }
  250. completionHandler(disposition, credential)
  251. }
  252. func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
  253. var bodyStream: NSInputStream?
  254. if taskNeedNewBodyStream != nil {
  255. bodyStream = taskNeedNewBodyStream!(session, task)
  256. }
  257. completionHandler(bodyStream)
  258. }
  259. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  260. if error != nil {
  261. self.error = error
  262. }
  263. queue.suspended = false
  264. }
  265. }
  266. class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  267. var dataTask: NSURLSessionDataTask! { return task as! NSURLSessionDataTask }
  268. private var mutableData: NSMutableData
  269. override var data: NSData? {
  270. return mutableData
  271. }
  272. private var expectedContentLength: Int64?
  273. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  274. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  275. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  276. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  277. var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  278. override init(task: NSURLSessionTask) {
  279. self.mutableData = NSMutableData()
  280. super.init(task: task)
  281. }
  282. // MARK: NSURLSessionDataDelegate
  283. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
  284. var disposition: NSURLSessionResponseDisposition = .Allow
  285. expectedContentLength = response.expectedContentLength
  286. if dataTaskDidReceiveResponse != nil {
  287. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  288. }
  289. completionHandler(disposition)
  290. }
  291. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
  292. dataTaskDidBecomeDownloadTask?(session, dataTask)
  293. }
  294. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  295. dataTaskDidReceiveData?(session, dataTask, data)
  296. mutableData.appendData(data)
  297. if let expectedContentLength = dataTask.response?.expectedContentLength {
  298. dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
  299. }
  300. }
  301. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
  302. var cachedResponse = proposedResponse
  303. if dataTaskWillCacheResponse != nil {
  304. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  305. }
  306. completionHandler(cachedResponse)
  307. }
  308. }
  309. }
  310. // MARK: - Validation
  311. extension Request {
  312. /**
  313. A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
  314. */
  315. public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
  316. /**
  317. Validates the request, using the specified closure.
  318. If validation fails, subsequent calls to response handlers will have an associated error.
  319. :param: validation A closure to validate the request.
  320. :returns: The request.
  321. */
  322. public func validate(validation: Validation) -> Self {
  323. delegate.queue.addOperationWithBlock {
  324. if self.response != nil && self.delegate.error == nil {
  325. if !validation(self.request, self.response!) {
  326. self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
  327. }
  328. }
  329. }
  330. return self
  331. }
  332. // MARK: Status Code
  333. /**
  334. Validates that the response has a status code in the specified range.
  335. If validation fails, subsequent calls to response handlers will have an associated error.
  336. :param: range The range of acceptable status codes.
  337. :returns: The request.
  338. */
  339. public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  340. return validate { (_, response) in
  341. return contains(acceptableStatusCode, response.statusCode)
  342. }
  343. }
  344. // MARK: Content-Type
  345. private struct MIMEType {
  346. let type: String
  347. let subtype: String
  348. init?(_ string: String) {
  349. let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
  350. if let type = components.first,
  351. subtype = components.last
  352. {
  353. self.type = type
  354. self.subtype = subtype
  355. } else {
  356. return nil
  357. }
  358. }
  359. func matches(MIME: MIMEType) -> Bool {
  360. switch (type, subtype) {
  361. case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
  362. return true
  363. default:
  364. return false
  365. }
  366. }
  367. }
  368. /**
  369. Validates that the response has a content type in the specified array.
  370. If validation fails, subsequent calls to response handlers will have an associated error.
  371. :param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
  372. :returns: The request.
  373. */
  374. public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  375. return validate {(_, response) in
  376. if let responseContentType = response.MIMEType,
  377. responseMIMEType = MIMEType(responseContentType)
  378. {
  379. for contentType in acceptableContentTypes {
  380. if let acceptableMIMEType = MIMEType(contentType)
  381. where acceptableMIMEType.matches(responseMIMEType)
  382. {
  383. return true
  384. }
  385. }
  386. }
  387. return false
  388. }
  389. }
  390. // MARK: Automatic
  391. /**
  392. Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
  393. If validation fails, subsequent calls to response handlers will have an associated error.
  394. :returns: The request.
  395. */
  396. public func validate() -> Self {
  397. let acceptableStatusCodes: Range<Int> = 200..<300
  398. let acceptableContentTypes: [String] = {
  399. if let accept = self.request.valueForHTTPHeaderField("Accept") {
  400. return accept.componentsSeparatedByString(",")
  401. }
  402. return ["*/*"]
  403. }()
  404. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  405. }
  406. }
  407. // MARK: - Upload
  408. extension Manager {
  409. private enum Uploadable {
  410. case Data(NSURLRequest, NSData)
  411. case File(NSURLRequest, NSURL)
  412. case Stream(NSURLRequest, NSInputStream)
  413. }
  414. private func upload(uploadable: Uploadable) -> Request {
  415. var uploadTask: NSURLSessionUploadTask!
  416. var HTTPBodyStream: NSInputStream?
  417. switch uploadable {
  418. case .Data(let request, let data):
  419. dispatch_sync(queue) {
  420. uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
  421. }
  422. case .File(let request, let fileURL):
  423. dispatch_sync(queue) {
  424. uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
  425. }
  426. case .Stream(let request, var stream):
  427. dispatch_sync(queue) {
  428. uploadTask = self.session.uploadTaskWithStreamedRequest(request)
  429. }
  430. HTTPBodyStream = stream
  431. }
  432. let request = Request(session: session, task: uploadTask)
  433. if HTTPBodyStream != nil {
  434. request.delegate.taskNeedNewBodyStream = { _, _ in
  435. return HTTPBodyStream
  436. }
  437. }
  438. delegate[request.delegate.task] = request.delegate
  439. if startRequestsImmediately {
  440. request.resume()
  441. }
  442. return request
  443. }
  444. // MARK: File
  445. /**
  446. Creates a request for uploading a file to the specified URL request.
  447. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  448. :param: URLRequest The URL request
  449. :param: file The file to upload
  450. :returns: The created upload request.
  451. */
  452. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  453. return upload(.File(URLRequest.URLRequest, file))
  454. }
  455. /**
  456. Creates a request for uploading a file to the specified URL request.
  457. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  458. :param: method The HTTP method.
  459. :param: URLString The URL string.
  460. :param: file The file to upload
  461. :returns: The created upload request.
  462. */
  463. public func upload(method: Method, _ URLString: URLStringConvertible, file: NSURL) -> Request {
  464. return upload(URLRequest(method, URLString), file: file)
  465. }
  466. // MARK: Data
  467. /**
  468. Creates a request for uploading data to the specified URL request.
  469. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  470. :param: URLRequest The URL request
  471. :param: data The data to upload
  472. :returns: The created upload request.
  473. */
  474. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  475. return upload(.Data(URLRequest.URLRequest, data))
  476. }
  477. /**
  478. Creates a request for uploading data to the specified URL request.
  479. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  480. :param: method The HTTP method.
  481. :param: URLString The URL string.
  482. :param: data The data to upload
  483. :returns: The created upload request.
  484. */
  485. public func upload(method: Method, _ URLString: URLStringConvertible, data: NSData) -> Request {
  486. return upload(URLRequest(method, URLString), data: data)
  487. }
  488. // MARK: Stream
  489. /**
  490. Creates a request for uploading a stream to the specified URL request.
  491. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  492. :param: URLRequest The URL request
  493. :param: stream The stream to upload
  494. :returns: The created upload request.
  495. */
  496. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  497. return upload(.Stream(URLRequest.URLRequest, stream))
  498. }
  499. /**
  500. Creates a request for uploading a stream to the specified URL request.
  501. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  502. :param: method The HTTP method.
  503. :param: URLString The URL string.
  504. :param: stream The stream to upload.
  505. :returns: The created upload request.
  506. */
  507. public func upload(method: Method, _ URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  508. return upload(URLRequest(method, URLString), stream: stream)
  509. }
  510. }
  511. extension Request {
  512. class UploadTaskDelegate: DataTaskDelegate {
  513. var uploadTask: NSURLSessionUploadTask! { return task as! NSURLSessionUploadTask }
  514. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  515. // MARK: NSURLSessionTaskDelegate
  516. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  517. progress.totalUnitCount = totalBytesExpectedToSend
  518. progress.completedUnitCount = totalBytesSent
  519. uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  520. }
  521. }
  522. }
  523. // MARK: - Download
  524. extension Manager {
  525. private enum Downloadable {
  526. case Request(NSURLRequest)
  527. case ResumeData(NSData)
  528. }
  529. private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
  530. var downloadTask: NSURLSessionDownloadTask!
  531. switch downloadable {
  532. case .Request(let request):
  533. dispatch_sync(queue) {
  534. downloadTask = self.session.downloadTaskWithRequest(request)
  535. }
  536. case .ResumeData(let resumeData):
  537. dispatch_sync(queue) {
  538. downloadTask = self.session.downloadTaskWithResumeData(resumeData)
  539. }
  540. }
  541. let request = Request(session: session, task: downloadTask)
  542. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  543. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  544. return destination(URL, downloadTask.response as! NSHTTPURLResponse)
  545. }
  546. }
  547. delegate[request.delegate.task] = request.delegate
  548. if startRequestsImmediately {
  549. request.resume()
  550. }
  551. return request
  552. }
  553. // MARK: Request
  554. /**
  555. Creates a download request using the shared manager instance for the specified method and URL string.
  556. :param: method The HTTP method.
  557. :param: URLString The URL string.
  558. :param: destination The closure used to determine the destination of the downloaded file.
  559. :returns: The created download request.
  560. */
  561. public func download(method: Method, _ URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
  562. return download(URLRequest(method, URLString), destination: destination)
  563. }
  564. /**
  565. Creates a request for downloading from the specified URL request.
  566. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  567. :param: URLRequest The URL request
  568. :param: destination The closure used to determine the destination of the downloaded file.
  569. :returns: The created download request.
  570. */
  571. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  572. return download(.Request(URLRequest.URLRequest), destination: destination)
  573. }
  574. // MARK: Resume Data
  575. /**
  576. Creates a request for downloading from the resume data produced from a previous request cancellation.
  577. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  578. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
  579. :param: destination The closure used to determine the destination of the downloaded file.
  580. :returns: The created download request.
  581. */
  582. public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
  583. return download(.ResumeData(resumeData), destination: destination)
  584. }
  585. }
  586. extension Request {
  587. /**
  588. A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
  589. */
  590. public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
  591. /**
  592. Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
  593. :param: directory The search path directory. `.DocumentDirectory` by default.
  594. :param: domain The search path domain mask. `.UserDomainMask` by default.
  595. :returns: A download file destination closure.
  596. */
  597. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
  598. return { (temporaryURL, response) -> (NSURL) in
  599. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
  600. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  601. }
  602. return temporaryURL
  603. }
  604. }
  605. class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  606. var downloadTask: NSURLSessionDownloadTask! { return task as! NSURLSessionDownloadTask }
  607. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  608. var resumeData: NSData?
  609. override var data: NSData? { return resumeData }
  610. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  611. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  612. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  613. // MARK: NSURLSessionDownloadDelegate
  614. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  615. if downloadTaskDidFinishDownloadingToURL != nil {
  616. let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  617. var fileManagerError: NSError?
  618. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  619. if fileManagerError != nil {
  620. error = fileManagerError
  621. }
  622. }
  623. }
  624. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  625. progress.totalUnitCount = totalBytesExpectedToWrite
  626. progress.completedUnitCount = totalBytesWritten
  627. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  628. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  629. }
  630. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  631. progress.totalUnitCount = expectedTotalBytes
  632. progress.completedUnitCount = fileOffset
  633. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  634. }
  635. }
  636. }
  637. // MARK: - Printable
  638. extension Request: Printable {
  639. /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
  640. public var description: String {
  641. var components: [String] = []
  642. if request.HTTPMethod != nil {
  643. components.append(request.HTTPMethod!)
  644. }
  645. components.append(request.URL!.absoluteString!)
  646. if response != nil {
  647. components.append("(\(response!.statusCode))")
  648. }
  649. return join(" ", components)
  650. }
  651. }
  652. extension Request: DebugPrintable {
  653. func cURLRepresentation() -> String {
  654. var components: [String] = ["$ curl -i"]
  655. let URL = request.URL
  656. if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
  657. components.append("-X \(request.HTTPMethod!)")
  658. }
  659. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  660. let protectionSpace = NSURLProtectionSpace(host: URL!.host!, port: URL!.port?.integerValue ?? 0, `protocol`: URL!.scheme!, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  661. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  662. for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
  663. components.append("-u \(credential.user!):\(credential.password!)")
  664. }
  665. } else {
  666. if let credential = delegate.credential {
  667. components.append("-u \(credential.user!):\(credential.password!)")
  668. }
  669. }
  670. }
  671. // Temporarily disabled on OS X due to build failure for CocoaPods
  672. // See https://github.com/CocoaPods/swift/issues/24
  673. #if !os(OSX)
  674. if let cookieStorage = session.configuration.HTTPCookieStorage,
  675. cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
  676. where !cookies.isEmpty
  677. {
  678. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
  679. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  680. }
  681. #endif
  682. if request.allHTTPHeaderFields != nil {
  683. for (field, value) in request.allHTTPHeaderFields! {
  684. switch field {
  685. case "Cookie":
  686. continue
  687. default:
  688. components.append("-H \"\(field): \(value)\"")
  689. }
  690. }
  691. }
  692. if session.configuration.HTTPAdditionalHeaders != nil {
  693. for (field, value) in session.configuration.HTTPAdditionalHeaders! {
  694. switch field {
  695. case "Cookie":
  696. continue
  697. default:
  698. components.append("-H \"\(field): \(value)\"")
  699. }
  700. }
  701. }
  702. if let HTTPBody = request.HTTPBody,
  703. escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
  704. {
  705. components.append("-d \"\(escapedBody)\"")
  706. }
  707. components.append("\"\(URL!.absoluteString!)\"")
  708. return join(" \\\n\t", components)
  709. }
  710. /// The textual representation used when written to an output stream, in the form of a cURL command.
  711. public var debugDescription: String {
  712. return cURLRepresentation()
  713. }
  714. }
  715. // MARK: - Response Serializers
  716. // MARK: String
  717. extension Request {
  718. /**
  719. Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
  720. :param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
  721. :returns: A string response serializer.
  722. */
  723. public class func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> Serializer {
  724. return { (_, response, data) in
  725. if data == nil || data?.length == 0 {
  726. return (nil, nil)
  727. }
  728. if encoding == nil {
  729. if let encodingName = response?.textEncodingName {
  730. encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
  731. }
  732. }
  733. let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding)
  734. return (string, nil)
  735. }
  736. }
  737. /**
  738. Adds a handler to be called once the request has finished.
  739. :param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
  740. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
  741. :returns: The request.
  742. */
  743. public func responseString(encoding: NSStringEncoding? = nil, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  744. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  745. completionHandler(request, response, string as? String, error)
  746. })
  747. }
  748. }
  749. // MARK: JSON
  750. extension Request {
  751. /**
  752. Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
  753. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  754. :returns: A JSON object response serializer.
  755. */
  756. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  757. return { (request, response, data) in
  758. if data == nil || data?.length == 0 {
  759. return (nil, nil)
  760. }
  761. var serializationError: NSError?
  762. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  763. return (JSON, serializationError)
  764. }
  765. }
  766. /**
  767. Adds a handler to be called once the request has finished.
  768. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  769. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
  770. :returns: The request.
  771. */
  772. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  773. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  774. completionHandler(request, response, JSON, error)
  775. })
  776. }
  777. }
  778. // MARK: Property List
  779. extension Request {
  780. /**
  781. Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
  782. :param: options The property list reading options. `0` by default.
  783. :returns: A property list object response serializer.
  784. */
  785. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  786. return { (request, response, data) in
  787. if data == nil || data?.length == 0 {
  788. return (nil, nil)
  789. }
  790. var propertyListSerializationError: NSError?
  791. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  792. return (plist, propertyListSerializationError)
  793. }
  794. }
  795. /**
  796. Adds a handler to be called once the request has finished.
  797. :param: options The property list reading options. `0` by default.
  798. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
  799. :returns: The request.
  800. */
  801. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  802. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  803. completionHandler(request, response, plist, error)
  804. })
  805. }
  806. }
  807. // MARK: - Convenience -
  808. func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
  809. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
  810. mutableURLRequest.HTTPMethod = method.rawValue
  811. return mutableURLRequest
  812. }
  813. // MARK: - Request
  814. /**
  815. Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
  816. :param: method The HTTP method.
  817. :param: URLString The URL string.
  818. :param: parameters The parameters. `nil` by default.
  819. :param: encoding The parameter encoding. `.URL` by default.
  820. :returns: The created request.
  821. */
  822. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  823. return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding)
  824. }
  825. /**
  826. Creates a request using the shared manager instance for the specified URL request.
  827. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  828. :param: URLRequest The URL request
  829. :returns: The created request.
  830. */
  831. public func request(URLRequest: URLRequestConvertible) -> Request {
  832. return Manager.sharedInstance.request(URLRequest.URLRequest)
  833. }
  834. // MARK: - Upload
  835. // MARK: File
  836. /**
  837. Creates an upload request using the shared manager instance for the specified method, URL string, and file.
  838. :param: method The HTTP method.
  839. :param: URLString The URL string.
  840. :param: file The file to upload.
  841. :returns: The created upload request.
  842. */
  843. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  844. return Manager.sharedInstance.upload(method, URLString, file: file)
  845. }
  846. /**
  847. Creates an upload request using the shared manager instance for the specified URL request and file.
  848. :param: URLRequest The URL request.
  849. :param: file The file to upload.
  850. :returns: The created upload request.
  851. */
  852. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  853. return Manager.sharedInstance.upload(URLRequest, file: file)
  854. }
  855. // MARK: Data
  856. /**
  857. Creates an upload request using the shared manager instance for the specified method, URL string, and data.
  858. :param: method The HTTP method.
  859. :param: URLString The URL string.
  860. :param: data The data to upload.
  861. :returns: The created upload request.
  862. */
  863. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  864. return Manager.sharedInstance.upload(method, URLString, data: data)
  865. }
  866. /**
  867. Creates an upload request using the shared manager instance for the specified URL request and data.
  868. :param: URLRequest The URL request.
  869. :param: data The data to upload.
  870. :returns: The created upload request.
  871. */
  872. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  873. return Manager.sharedInstance.upload(URLRequest, data: data)
  874. }
  875. // MARK: Stream
  876. /**
  877. Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
  878. :param: method The HTTP method.
  879. :param: URLString The URL string.
  880. :param: stream The stream to upload.
  881. :returns: The created upload request.
  882. */
  883. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  884. return Manager.sharedInstance.upload(method, URLString, stream: stream)
  885. }
  886. /**
  887. Creates an upload request using the shared manager instance for the specified URL request and stream.
  888. :param: URLRequest The URL request.
  889. :param: stream The stream to upload.
  890. :returns: The created upload request.
  891. */
  892. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  893. return Manager.sharedInstance.upload(URLRequest, stream: stream)
  894. }
  895. // MARK: - Download
  896. // MARK: URL Request
  897. /**
  898. Creates a download request using the shared manager instance for the specified method and URL string.
  899. :param: method The HTTP method.
  900. :param: URLString The URL string.
  901. :param: destination The closure used to determine the destination of the downloaded file.
  902. :returns: The created download request.
  903. */
  904. public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
  905. return Manager.sharedInstance.download(method, URLString, destination: destination)
  906. }
  907. /**
  908. Creates a download request using the shared manager instance for the specified URL request.
  909. :param: URLRequest The URL request.
  910. :param: destination The closure used to determine the destination of the downloaded file.
  911. :returns: The created download request.
  912. */
  913. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  914. return Manager.sharedInstance.download(URLRequest, destination: destination)
  915. }
  916. // MARK: Resume Data
  917. /**
  918. Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
  919. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
  920. :param: destination The closure used to determine the destination of the downloaded file.
  921. :returns: The created download request.
  922. */
  923. public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
  924. return Manager.sharedInstance.download(data, destination: destination)
  925. }