MultipartFormData.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // MultipartFormData.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. #if os(iOS)
  24. import MobileCoreServices
  25. #elseif os(OSX)
  26. import CoreServices
  27. #endif
  28. /**
  29. Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
  30. multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
  31. to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
  32. data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
  33. larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
  34. For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
  35. and the w3 form documentation.
  36. - http://www.ietf.org/rfc/rfc2388.txt
  37. - http://www.ietf.org/rfc/rfc2045.txt
  38. - http://www.w3.org/TR/html401/interact/forms.html#h-17.13
  39. */
  40. public class MultipartFormData {
  41. // MARK: - Helper Types
  42. /**
  43. Used to specify whether encoding was successful.
  44. */
  45. public enum EncodingResult {
  46. case Success(NSData)
  47. case Failure(NSError)
  48. }
  49. struct EncodingCharacters {
  50. static let CRLF = "\r\n"
  51. }
  52. struct BoundaryGenerator {
  53. enum BoundaryType {
  54. case Initial, Encapsulated, Final
  55. }
  56. static func randomBoundary() -> String {
  57. return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
  58. }
  59. static func boundaryData(#boundaryType: BoundaryType, boundary: String) -> NSData {
  60. let boundaryText: String
  61. switch boundaryType {
  62. case .Initial:
  63. boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
  64. case .Encapsulated:
  65. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
  66. case .Final:
  67. boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
  68. }
  69. return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  70. }
  71. }
  72. class BodyPart {
  73. let headers: [String: String]
  74. let bodyStream: NSInputStream
  75. let bodyContentLength: UInt64
  76. var hasInitialBoundary = false
  77. var hasFinalBoundary = false
  78. init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
  79. self.headers = headers
  80. self.bodyStream = bodyStream
  81. self.bodyContentLength = bodyContentLength
  82. }
  83. }
  84. // MARK: - Properties
  85. /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
  86. public var contentType: String { return "multipart/form-data; boundary=\(self.boundary)" }
  87. /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
  88. public var contentLength: UInt64 { return self.bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
  89. /// The boundary used to separate the body parts in the encoded form data.
  90. public let boundary: String
  91. private var bodyParts: [BodyPart]
  92. private let streamBufferSize: Int
  93. // MARK: - Lifecycle
  94. /**
  95. Creates a multipart form data object.
  96. :returns: The multipart form data object.
  97. */
  98. public init() {
  99. self.boundary = BoundaryGenerator.randomBoundary()
  100. self.bodyParts = []
  101. /**
  102. * The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
  103. * information, please refer to the following article:
  104. * - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
  105. */
  106. self.streamBufferSize = 1024
  107. }
  108. // MARK: - Body Parts
  109. /**
  110. Creates a body part from the file and appends it to the multipart form data object.
  111. The body part data will be encoded using the following format:
  112. - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
  113. - `Content-Type: #{generated mimeType}` (HTTP Header)
  114. - Encoded file data
  115. - Multipart form boundary
  116. The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
  117. `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
  118. system associated MIME type.
  119. :param: URL The URL of the file whose content will be encoded into the multipart form data.
  120. :param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
  121. :returns: An `NSError` if an error occurred, `nil` otherwise.
  122. */
  123. public func appendBodyPart(fileURL URL: NSURL, name: String) -> NSError? {
  124. if let
  125. fileName = URL.lastPathComponent,
  126. pathExtension = URL.pathExtension
  127. {
  128. let mimeType = mimeTypeForPathExtension(pathExtension)
  129. return appendBodyPart(fileURL: URL, name: name, fileName: fileName, mimeType: mimeType)
  130. }
  131. let failureReason = "Failed to extract the fileName of the provided URL: \(URL)"
  132. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  133. return NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo)
  134. }
  135. /**
  136. Creates a body part from the file and appends it to the multipart form data object.
  137. The body part data will be encoded using the following format:
  138. - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
  139. - Content-Type: #{mimeType} (HTTP Header)
  140. - Encoded file data
  141. - Multipart form boundary
  142. :param: URL The URL of the file whose content will be encoded into the multipart form data.
  143. :param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
  144. :param: fileName The filename to associate with the file content in the `Content-Disposition` HTTP header.
  145. :param: mimeType The MIME type to associate with the file content in the `Content-Type` HTTP header.
  146. :returns: An `NSError` if an error occurred, `nil` otherwise.
  147. */
  148. public func appendBodyPart(fileURL URL: NSURL, name: String, fileName: String, mimeType: String) -> NSError? {
  149. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  150. var isDirectory: ObjCBool = false
  151. if !URL.fileURL {
  152. return errorWithCode(NSURLErrorBadURL, failureReason: "The URL does not point to a file URL: \(URL)")
  153. } else if !URL.checkResourceIsReachableAndReturnError(nil) {
  154. return errorWithCode(NSURLErrorBadURL, failureReason: "The URL is not reachable: \(URL)")
  155. } else if NSFileManager.defaultManager().fileExistsAtPath(URL.path!, isDirectory: &isDirectory) && isDirectory {
  156. return errorWithCode(NSURLErrorBadURL, failureReason: "The URL is a directory, not a file: \(URL)")
  157. }
  158. let bodyContentLength: UInt64
  159. var fileAttributesError: NSError?
  160. if let
  161. path = URL.path,
  162. attributes = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: &fileAttributesError),
  163. fileSize = (attributes[NSFileSize] as? NSNumber)?.unsignedLongLongValue
  164. {
  165. bodyContentLength = fileSize
  166. } else {
  167. return errorWithCode(NSURLErrorBadURL, failureReason: "Could not fetch attributes from the URL: \(URL)")
  168. }
  169. if let bodyStream = NSInputStream(URL: URL) {
  170. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  171. self.bodyParts.append(bodyPart)
  172. } else {
  173. let failureReason = "Failed to create an input stream from the URL: \(URL)"
  174. return errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  175. }
  176. return nil
  177. }
  178. /**
  179. Creates a body part from the data and appends it to the multipart form data object.
  180. The body part data will be encoded using the following format:
  181. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  182. - `Content-Type: #{mimeType}` (HTTP Header)
  183. - Encoded file data
  184. - Multipart form boundary
  185. :param: data The data to encode into the multipart form data.
  186. :param: name The name to associate with the data in the `Content-Disposition` HTTP header.
  187. :param: fileName The filename to associate with the data in the `Content-Disposition` HTTP header.
  188. :param: mimeType The MIME type to associate with the data in the `Content-Type` HTTP header.
  189. */
  190. public func appendBodyPart(fileData data: NSData, name: String, fileName: String, mimeType: String) {
  191. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  192. let bodyStream = NSInputStream(data: data)
  193. let bodyContentLength = UInt64(data.length)
  194. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  195. self.bodyParts.append(bodyPart)
  196. }
  197. /**
  198. Creates a body part from the data and appends it to the multipart form data object.
  199. The body part data will be encoded using the following format:
  200. - `Content-Disposition: form-data; name=#{name}` (HTTP Header)
  201. - Encoded file data
  202. - Multipart form boundary
  203. :param: data The data to encode into the multipart form data.
  204. :param: name The name to associate with the data in the `Content-Disposition` HTTP header.
  205. */
  206. public func appendBodyPart(#data: NSData, name: String) {
  207. let headers = contentHeaders(name: name)
  208. let bodyStream = NSInputStream(data: data)
  209. let bodyContentLength = UInt64(data.length)
  210. let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
  211. self.bodyParts.append(bodyPart)
  212. }
  213. /**
  214. Creates a body part from the stream and appends it to the multipart form data object.
  215. The body part data will be encoded using the following format:
  216. - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
  217. - `Content-Type: #{mimeType}` (HTTP Header)
  218. - Encoded file data
  219. - Multipart form boundary
  220. :param: stream The input stream to encode in the multipart form data.
  221. :param: name The name to associate with the stream content in the `Content-Disposition` HTTP header.
  222. :param: fileName The filename to associate with the stream content in the `Content-Disposition` HTTP header.
  223. :param: mimeType The MIME type to associate with the stream content in the `Content-Type` HTTP header.
  224. */
  225. public func appendBodyPart(#stream: NSInputStream, name: String, fileName: String, length: UInt64, mimeType: String) {
  226. let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
  227. let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
  228. self.bodyParts.append(bodyPart)
  229. }
  230. // MARK: - Data Extraction
  231. /**
  232. Encodes all the appended body parts into a single `NSData` object.
  233. It is important to note that this method will load all the appended body parts into memory all at the same
  234. time. This method should only be used when the encoded data will have a small memory footprint. For large data
  235. cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
  236. :returns: EncodingResult containing an `NSData` object if the encoding succeeded, an `NSError` otherwise.
  237. */
  238. public func encode() -> EncodingResult {
  239. var encoded = NSMutableData()
  240. self.bodyParts.first?.hasInitialBoundary = true
  241. self.bodyParts.last?.hasFinalBoundary = true
  242. for bodyPart in self.bodyParts {
  243. let encodedDataResult = encodeBodyPart(bodyPart)
  244. switch encodedDataResult {
  245. case .Failure:
  246. return encodedDataResult
  247. case let .Success(data):
  248. encoded.appendData(data)
  249. }
  250. }
  251. return .Success(encoded)
  252. }
  253. /**
  254. Writes the appended body parts into the given file URL asynchronously and calls the `completionHandler`
  255. when finished.
  256. This process is facilitated by reading and writing with input and output streams, respectively. Thus,
  257. this approach is very memory efficient and should be used for large body part data.
  258. :param: fileURL The file URL to write the multipart form data into.
  259. :param: completionHandler A closure to be executed when writing is finished.
  260. */
  261. public func writeEncodedDataToDisk(fileURL: NSURL, completionHandler: (NSError?) -> Void) {
  262. var error: NSError?
  263. if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
  264. let failureReason = "A file already exists at the given file URL: \(fileURL)"
  265. error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  266. } else if !fileURL.fileURL {
  267. let failureReason = "The URL does not point to a valid file: \(fileURL)"
  268. error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
  269. }
  270. if let error = error {
  271. completionHandler(error)
  272. return
  273. }
  274. let outputStream: NSOutputStream
  275. if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
  276. outputStream = possibleOutputStream
  277. } else {
  278. let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
  279. let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
  280. completionHandler(error)
  281. return
  282. }
  283. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  284. outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  285. outputStream.open()
  286. self.bodyParts.first?.hasInitialBoundary = true
  287. self.bodyParts.last?.hasFinalBoundary = true
  288. var error: NSError?
  289. for bodyPart in self.bodyParts {
  290. if let writeError = self.writeBodyPart(bodyPart, toOutputStream: outputStream) {
  291. error = writeError
  292. break
  293. }
  294. }
  295. outputStream.close()
  296. outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  297. dispatch_async(dispatch_get_main_queue()) {
  298. completionHandler(error)
  299. }
  300. }
  301. }
  302. // MARK: - Private - Body Part Encoding
  303. private func encodeBodyPart(bodyPart: BodyPart) -> EncodingResult {
  304. let encoded = NSMutableData()
  305. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  306. encoded.appendData(initialData)
  307. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  308. encoded.appendData(headerData)
  309. let bodyStreamResult = encodeBodyStreamDataForBodyPart(bodyPart)
  310. switch bodyStreamResult {
  311. case .Failure:
  312. return bodyStreamResult
  313. case let .Success(data):
  314. encoded.appendData(data)
  315. }
  316. if bodyPart.hasFinalBoundary {
  317. encoded.appendData(finalBoundaryData())
  318. }
  319. return .Success(encoded)
  320. }
  321. private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
  322. var headerText = ""
  323. for (key, value) in bodyPart.headers {
  324. headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
  325. }
  326. headerText += EncodingCharacters.CRLF
  327. return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
  328. }
  329. private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) -> EncodingResult {
  330. let inputStream = bodyPart.bodyStream
  331. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  332. inputStream.open()
  333. var error: NSError?
  334. let encoded = NSMutableData()
  335. while inputStream.hasBytesAvailable {
  336. var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
  337. let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
  338. if inputStream.streamError != nil {
  339. error = inputStream.streamError
  340. break
  341. }
  342. if bytesRead > 0 {
  343. encoded.appendBytes(buffer, length: bytesRead)
  344. } else if bytesRead < 0 {
  345. let failureReason = "Failed to read from input stream: \(inputStream)"
  346. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  347. break
  348. } else {
  349. break
  350. }
  351. }
  352. inputStream.close()
  353. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  354. if let error = error {
  355. return .Failure(error)
  356. }
  357. return .Success(encoded)
  358. }
  359. // MARK: - Private - Writing Body Part to Output Stream
  360. private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  361. if let error = writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  362. return error
  363. }
  364. if let error = writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  365. return error
  366. }
  367. if let error = writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) {
  368. return error
  369. }
  370. if let error = writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
  371. return error
  372. }
  373. return nil
  374. }
  375. private func writeInitialBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  376. let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
  377. return writeData(initialData, toOutputStream: outputStream)
  378. }
  379. private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  380. let headerData = encodeHeaderDataForBodyPart(bodyPart)
  381. return writeData(headerData, toOutputStream: outputStream)
  382. }
  383. private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  384. var error: NSError?
  385. let inputStream = bodyPart.bodyStream
  386. inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  387. inputStream.open()
  388. while inputStream.hasBytesAvailable {
  389. var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
  390. let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
  391. if inputStream.streamError != nil {
  392. error = inputStream.streamError
  393. break
  394. }
  395. if bytesRead > 0 {
  396. if buffer.count != bytesRead {
  397. buffer = Array(buffer[0..<bytesRead])
  398. }
  399. if let writeError = writeBuffer(&buffer, toOutputStream: outputStream) {
  400. error = writeError
  401. break
  402. }
  403. } else if bytesRead < 0 {
  404. let failureReason = "Failed to read from input stream: \(inputStream)"
  405. error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
  406. break
  407. } else {
  408. break
  409. }
  410. }
  411. inputStream.close()
  412. inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
  413. return error
  414. }
  415. private func writeFinalBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
  416. if bodyPart.hasFinalBoundary {
  417. return writeData(finalBoundaryData(), toOutputStream: outputStream)
  418. }
  419. return nil
  420. }
  421. // MARK: - Private - Writing Buffered Data to Output Stream
  422. private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) -> NSError? {
  423. var buffer = [UInt8](count: data.length, repeatedValue: 0)
  424. data.getBytes(&buffer, length: data.length)
  425. return writeBuffer(&buffer, toOutputStream: outputStream)
  426. }
  427. private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) -> NSError? {
  428. var error: NSError?
  429. var bytesToWrite = buffer.count
  430. while bytesToWrite > 0 {
  431. if outputStream.hasSpaceAvailable {
  432. let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
  433. if outputStream.streamError != nil {
  434. error = outputStream.streamError
  435. break
  436. }
  437. if bytesWritten < 0 {
  438. let failureReason = "Failed to write to output stream: \(outputStream)"
  439. error = errorWithCode(AlamofireOutputStreamWriteFailed, failureReason: failureReason)
  440. break
  441. }
  442. bytesToWrite -= bytesWritten
  443. if bytesToWrite > 0 {
  444. buffer = Array(buffer[bytesWritten..<buffer.count])
  445. }
  446. } else if outputStream.streamError != nil {
  447. error = outputStream.streamError
  448. break
  449. }
  450. }
  451. return error
  452. }
  453. // MARK: - Private - Mime Type
  454. private func mimeTypeForPathExtension(pathExtension: String) -> String {
  455. let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil).takeRetainedValue()
  456. if let contentType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType) {
  457. return contentType.takeRetainedValue() as String
  458. }
  459. return "application/octet-stream"
  460. }
  461. // MARK: - Private - Content Headers
  462. private func contentHeaders(#name: String) -> [String: String] {
  463. return ["Content-Disposition": "form-data; name=\"\(name)\""]
  464. }
  465. private func contentHeaders(#name: String, fileName: String, mimeType: String) -> [String: String] {
  466. return [
  467. "Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
  468. "Content-Type": "\(mimeType)"
  469. ]
  470. }
  471. // MARK: - Private - Boundary Encoding
  472. private func initialBoundaryData() -> NSData {
  473. return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: self.boundary)
  474. }
  475. private func encapsulatedBoundaryData() -> NSData {
  476. return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: self.boundary)
  477. }
  478. private func finalBoundaryData() -> NSData {
  479. return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: self.boundary)
  480. }
  481. // MARK: - Private - Errors
  482. private func errorWithCode(code: Int, failureReason: String) -> NSError {
  483. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  484. return NSError(domain: AlamofireErrorDomain, code: code, userInfo: userInfo)
  485. }
  486. }