MultipartFormData.swift 25 KB

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