├── MarvelAPI.playground ├── contents.xcplayground ├── Sources │ ├── Models │ │ ├── ComicCharacter.swift │ │ ├── MarvelError.swift │ │ ├── Comic.swift │ │ ├── DataContainer.swift │ │ ├── APIRequest.swift │ │ ├── MarvelResponse.swift │ │ └── Image.swift │ ├── Requests │ │ ├── GetComic.swift │ │ ├── GetCharacters.swift │ │ └── GetComics.swift │ ├── Utils │ │ ├── URLQueryItemEncoder.swift │ │ ├── HTTPParameter.swift │ │ └── md5.swift │ └── MarvelAPIClient.swift └── Contents.swift ├── README.md ├── .gitignore └── LICENSE /MarvelAPI.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/ComicCharacter.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct ComicCharacter: Decodable { 4 | public let id: Int 5 | public let name: String? 6 | public let description: String? 7 | public let thumbnail: Image? 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MarvelAPI 2 | 3 | Proof of concept API Client written in Swift 5 to easily read the Marvel API. 4 | 5 | You need Xcode 10.2 to run this playground. 6 | 7 | ### [Related Blog Post](https://medium.com/makingtuenti/writing-a-scalable-api-client-in-swift-4-b3c6f7f3f3fb) 8 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/MarvelError.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Dumb error to model simple errors 4 | /// In a real implementation this should be more exhaustive 5 | public enum MarvelError: Error { 6 | case encoding 7 | case decoding 8 | case server(message: String) 9 | } 10 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/Comic.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct Comic: Decodable { 4 | public let id: Int 5 | public let title: String? 6 | public let issueNumber: Double? 7 | public let description: String? 8 | public let pageCount: Int? 9 | public let thumbnail: Image? 10 | } 11 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/DataContainer.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// All successful responses return this, and contains all 4 | /// the metainformation about the returned chunk. 5 | public struct DataContainer: Decodable { 6 | public let offset: Int 7 | public let limit: Int 8 | public let total: Int 9 | public let count: Int 10 | public let results: Results 11 | } 12 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Requests/GetComic.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct GetComic: APIRequest { 4 | public typealias Response = [Comic] 5 | 6 | // Notice how we create a composed resourceName 7 | public var resourceName: String { 8 | return "comics/\(comicId)" 9 | } 10 | 11 | // Parameters 12 | private let comicId: Int 13 | 14 | public init(comicId: Int) { 15 | self.comicId = comicId 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Utils/URLQueryItemEncoder.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Encodes any encodable to a URLQueryItem list 4 | enum URLQueryItemEncoder { 5 | static func encode(_ encodable: T) throws -> [URLQueryItem] { 6 | let parametersData = try JSONEncoder().encode(encodable) 7 | let parameters = try JSONDecoder().decode([String: HTTPParameter].self, from: parametersData) 8 | return parameters.map { URLQueryItem(name: $0, value: $1.description) } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/APIRequest.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// All requests must conform to this protocol 4 | /// - Discussion: You must conform to Encodable too, so that all stored public parameters 5 | /// of types conforming this protocol will be encoded as parameters. 6 | public protocol APIRequest: Encodable { 7 | /// Response (will be wrapped with a DataContainer) 8 | associatedtype Response: Decodable 9 | 10 | /// Endpoint for this request (the last part of the URL) 11 | var resourceName: String { get } 12 | } 13 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/MarvelResponse.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Top level response for every request to the Marvel API 4 | /// Everything in the API seems to be optional, so we cannot rely on having values here 5 | public struct MarvelResponse: Decodable { 6 | /// Whether it was ok or not 7 | public let status: String? 8 | /// Message that usually gives more information about some error 9 | public let message: String? 10 | /// Requested data 11 | public let data: DataContainer? 12 | } 13 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Requests/GetCharacters.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct GetCharacters: APIRequest { 4 | public typealias Response = [ComicCharacter] 5 | 6 | public var resourceName: String { 7 | return "characters" 8 | } 9 | 10 | // Parameters 11 | public let name: String? 12 | public let nameStartsWith: String? 13 | public let limit: Int? 14 | public let offset: Int? 15 | 16 | // Note that nil parameters will not be used 17 | public init(name: String? = nil, 18 | nameStartsWith: String? = nil, 19 | limit: Int? = nil, 20 | offset: Int? = nil) { 21 | self.name = name 22 | self.nameStartsWith = nameStartsWith 23 | self.limit = limit 24 | self.offset = offset 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Models/Image.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | /// Common object for images coming from the Marvel API 4 | /// Shows how to fully conform to Decodable 5 | public struct Image: Decodable { 6 | /// Server sends the remote URL splits in two: the path and the extension 7 | enum ImageKeys: String, CodingKey { 8 | case path = "path" 9 | case fileExtension = "extension" 10 | } 11 | 12 | /// The remote URL for this image 13 | public let url: URL 14 | 15 | public init(from decoder: Decoder) throws { 16 | let container = try decoder.container(keyedBy: ImageKeys.self) 17 | 18 | let path = try container.decode(String.self, forKey: .path) 19 | let fileExtension = try container.decode(String.self, forKey: .fileExtension) 20 | 21 | guard let url = URL(string: "\(path).\(fileExtension)") else { throw MarvelError.decoding } 22 | 23 | self.url = url 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Requests/GetComics.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct GetComics: APIRequest { 4 | // When encountered with this kind of enums, it will spit out the raw value 5 | public enum ComicFormat: String, Encodable { 6 | case comic = "comic" 7 | case digital = "digital comic" 8 | case hardcover = "hardcover" 9 | } 10 | 11 | public typealias Response = [Comic] 12 | 13 | public var resourceName: String { 14 | return "comics" 15 | } 16 | 17 | // Parameters 18 | public let title: String? 19 | public let titleStartsWith: String? 20 | public let format: ComicFormat? 21 | public let limit: Int? 22 | public let offset: Int? 23 | 24 | // Note that nil parameters will not be used 25 | public init(title: String? = nil, 26 | titleStartsWith: String? = nil, 27 | format: ComicFormat? = nil, 28 | limit: Int? = nil, 29 | offset: Int? = nil) { 30 | self.title = title 31 | self.titleStartsWith = titleStartsWith 32 | self.format = format 33 | self.limit = limit 34 | self.offset = offset 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Utils/HTTPParameter.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | // Utility type so that we can decode any type of HTTP parameter 4 | // Useful when we have mixed types in a HTTP request 5 | enum HTTPParameter: CustomStringConvertible, Decodable { 6 | case string(String) 7 | case bool(Bool) 8 | case int(Int) 9 | case double(Double) 10 | 11 | init(from decoder: Decoder) throws { 12 | let container = try decoder.singleValueContainer() 13 | 14 | if let string = try? container.decode(String.self) { 15 | self = .string(string) 16 | } else if let bool = try? container.decode(Bool.self) { 17 | self = .bool(bool) 18 | } else if let int = try? container.decode(Int.self) { 19 | self = .int(int) 20 | } else if let double = try? container.decode(Double.self) { 21 | self = .double(double) 22 | } else { 23 | throw MarvelError.decoding 24 | } 25 | } 26 | 27 | var description: String { 28 | switch self { 29 | case .string(let string): 30 | return string 31 | case .bool(let bool): 32 | return String(describing: bool) 33 | case .int(let int): 34 | return String(describing: int) 35 | case .double(let double): 36 | return String(describing: double) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | .DS_Store 25 | 26 | ## Obj-C/Swift specific 27 | *.hmap 28 | *.ipa 29 | *.dSYM.zip 30 | *.dSYM 31 | 32 | ## Playgrounds 33 | timeline.xctimeline 34 | playground.xcworkspace 35 | 36 | # Swift Package Manager 37 | # 38 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 39 | # Packages/ 40 | # Package.pins 41 | .build/ 42 | 43 | # CocoaPods 44 | # 45 | # We recommend against adding the Pods directory to your .gitignore. However 46 | # you should judge for yourself, the pros and cons are mentioned at: 47 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 48 | # 49 | # Pods/ 50 | 51 | # Carthage 52 | # 53 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 54 | # Carthage/Checkouts 55 | 56 | Carthage/Build 57 | 58 | # fastlane 59 | # 60 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 61 | # screenshots whenever they are needed. 62 | # For more information about the recommended setup visit: 63 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 64 | 65 | fastlane/report.xml 66 | fastlane/Preview.html 67 | fastlane/screenshots 68 | fastlane/test_output 69 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import PlaygroundSupport 3 | 4 | // Put your own keys! 5 | // You can freely get a key here: https://developer.marvel.com/docs 6 | let apiClient = MarvelAPIClient(publicKey: "650e801e1408159969078d2a1361c71c", 7 | privateKey: "20112b45612fd05f0d21d80d70bc8c971695c7f1") 8 | 9 | // A simple request with no parameters 10 | apiClient.send(GetCharacters()) { response in 11 | print("\nGetCharacters finished:") 12 | 13 | response.map { dataContainer in 14 | for character in dataContainer.results { 15 | print(" Title: \(character.name ?? "Unnamed character")") 16 | print(" Thumbnail: \(character.thumbnail?.url.absoluteString ?? "None")") 17 | } 18 | } 19 | } 20 | 21 | // Another request filling interesting optional parameters, a string and an enum 22 | apiClient.send(GetComics(titleStartsWith: "Avengers", format: .digital)) { response in 23 | print("\nGetComics finished:") 24 | 25 | do { 26 | let dataContainer = try response.get() 27 | 28 | for comic in dataContainer.results { 29 | print(" Title: \(comic.title ?? "Unnamed comic")") 30 | print(" Thumbnail: \(comic.thumbnail?.url.absoluteString ?? "None")") 31 | } 32 | } catch { 33 | print(error) 34 | } 35 | } 36 | 37 | // Yet another request with a mandatory parameter 38 | apiClient.send(GetComic(comicId: 61537)) { response in 39 | print("\nGetComic finished:") 40 | 41 | switch response { 42 | case .success(let dataContainer): 43 | let comic = dataContainer.results.first 44 | 45 | print(" Title: \(comic?.title ?? "Unnamed comic")") 46 | print(" Thumbnail: \(comic?.thumbnail?.url.absoluteString ?? "None")") 47 | case .failure(let error): 48 | print(error) 49 | } 50 | } 51 | 52 | PlaygroundPage.current.needsIndefiniteExecution = true 53 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/MarvelAPIClient.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public typealias ResultCallback = (Result) -> Void 4 | 5 | /// Implementation of a generic-based Marvel API client 6 | public class MarvelAPIClient { 7 | private let baseEndpointUrl = URL(string: "https://gateway.marvel.com:443/v1/public/")! 8 | private let session = URLSession(configuration: .default) 9 | 10 | private let publicKey: String 11 | private let privateKey: String 12 | 13 | public init(publicKey: String, privateKey: String) { 14 | self.publicKey = publicKey 15 | self.privateKey = privateKey 16 | } 17 | 18 | /// Sends a request to Marvel servers, calling the completion method when finished 19 | public func send(_ request: T, completion: @escaping ResultCallback>) { 20 | let endpoint = self.endpoint(for: request) 21 | 22 | let task = session.dataTask(with: URLRequest(url: endpoint)) { data, response, error in 23 | if let data = data { 24 | do { 25 | // Decode the top level response, and look up the decoded response to see 26 | // if it's a success or a failure 27 | let marvelResponse = try JSONDecoder().decode(MarvelResponse.self, from: data) 28 | 29 | if let dataContainer = marvelResponse.data { 30 | completion(.success(dataContainer)) 31 | } else if let message = marvelResponse.message { 32 | completion(.failure(MarvelError.server(message: message))) 33 | } else { 34 | completion(.failure(MarvelError.decoding)) 35 | } 36 | } catch { 37 | completion(.failure(error)) 38 | } 39 | } else if let error = error { 40 | completion(.failure(error)) 41 | } 42 | } 43 | task.resume() 44 | } 45 | 46 | /// Encodes a URL based on the given request 47 | /// Everything needed for a public request to Marvel servers is encoded directly in this URL 48 | private func endpoint(for request: T) -> URL { 49 | guard let baseUrl = URL(string: request.resourceName, relativeTo: baseEndpointUrl) else { 50 | fatalError("Bad resourceName: \(request.resourceName)") 51 | } 52 | 53 | var components = URLComponents(url: baseUrl, resolvingAgainstBaseURL: true)! 54 | 55 | // Common query items needed for all Marvel requests 56 | let timestamp = "\(Date().timeIntervalSince1970)" 57 | let hash = "\(timestamp)\(privateKey)\(publicKey)".md5 58 | let commonQueryItems = [ 59 | URLQueryItem(name: "ts", value: timestamp), 60 | URLQueryItem(name: "hash", value: hash), 61 | URLQueryItem(name: "apikey", value: publicKey) 62 | ] 63 | 64 | // Custom query items needed for this specific request 65 | let customQueryItems: [URLQueryItem] 66 | 67 | do { 68 | customQueryItems = try URLQueryItemEncoder.encode(request) 69 | } catch { 70 | fatalError("Wrong parameters: \(error)") 71 | } 72 | 73 | components.queryItems = commonQueryItems + customQueryItems 74 | 75 | // Construct the final URL with all the previous data 76 | return components.url! 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /MarvelAPI.playground/Sources/Utils/md5.swift: -------------------------------------------------------------------------------- 1 | // MARK: - Utilities 2 | 3 | public typealias Byte = UInt8 4 | typealias Word = UInt32 5 | 6 | public struct Digest { 7 | public let digest: [Byte] 8 | 9 | init(_ digest: [Byte]) { 10 | assert(digest.count == 16) 11 | self.digest = digest 12 | } 13 | 14 | public var checksum: String { 15 | return encodeMD5(digest: digest) 16 | } 17 | } 18 | 19 | private func F(_ b: Word, _ c: Word, _ d: Word) -> Word { 20 | return (b & c) | ((~b) & d) 21 | } 22 | 23 | private func G(_ b: Word, _ c: Word, _ d: Word) -> Word { 24 | return (b & d) | (c & (~d)) 25 | } 26 | 27 | private func H(_ b: Word, _ c: Word, _ d: Word) -> Word { 28 | return b ^ c ^ d 29 | } 30 | 31 | private func I(_ b: Word, _ c: Word, _ d: Word) -> Word { 32 | return c ^ (b | (~d)) 33 | } 34 | 35 | private func rotateLeft(_ x: Word, by: Word) -> Word { 36 | return ((x << by) & 0xFFFFFFFF) | (x >> (32 - by)) 37 | } 38 | 39 | // MARK: - Calculating a MD5 digest of bytes from bytes 40 | public func calculateMD5(_ bytes: [Byte]) -> Digest { 41 | // Initialization 42 | let s: [Word] = [ 43 | 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 44 | 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 45 | 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 46 | 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 47 | ] 48 | let K: [Word] = [ 49 | 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 50 | 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 51 | 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 52 | 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 53 | 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 54 | 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 55 | 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 56 | 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 57 | 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 58 | 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 59 | 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 60 | 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 61 | 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 62 | 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 63 | 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 64 | 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 65 | ] 66 | 67 | var a0: Word = 0x67452301 // A 68 | var b0: Word = 0xefcdab89 // B 69 | var c0: Word = 0x98badcfe // C 70 | var d0: Word = 0x10325476 // D 71 | 72 | // Pad message with a single bit "1" 73 | var message = bytes 74 | 75 | let originalLength = bytes.count 76 | let bitLength = UInt64(originalLength * 8) 77 | 78 | message.append(0x80) 79 | 80 | // Pad message with bit "0" until message length is 64 bits fewer than 512 81 | repeat { 82 | message.append(0x0) 83 | } while (message.count * 8) % 512 != 448 84 | 85 | message.append(Byte((bitLength >> 0) & 0xFF)) 86 | message.append(Byte((bitLength >> 8) & 0xFF)) 87 | message.append(Byte((bitLength >> 16) & 0xFF)) 88 | message.append(Byte((bitLength >> 24) & 0xFF)) 89 | message.append(Byte((bitLength >> 32) & 0xFF)) 90 | message.append(Byte((bitLength >> 40) & 0xFF)) 91 | message.append(Byte((bitLength >> 48) & 0xFF)) 92 | message.append(Byte((bitLength >> 56) & 0xFF)) 93 | 94 | let newBitLength = message.count * 8 95 | 96 | assert(newBitLength % 512 == 0) 97 | 98 | // Transform 99 | 100 | let chunkLength = 512 // 512-bit 101 | let chunkLengthInBytes = chunkLength / 8 // 64-bytes 102 | let totalChunks = newBitLength / chunkLength 103 | 104 | assert(totalChunks >= 1) 105 | 106 | for chunk in 0..= 16 && i <= 31 { 137 | f = G(B, C, D) 138 | g = ((5*i + 1) % 16) 139 | } else if i >= 32 && i <= 47 { 140 | f = H(B, C, D) 141 | g = ((3*i + 5) % 16) 142 | } else if i >= 48 && i <= 63 { 143 | f = I(B, C, D) 144 | g = ((7*i) % 16) 145 | } 146 | 147 | let dTemp = D 148 | D = C 149 | C = B 150 | 151 | let x = A &+ f &+ K[i] &+ M[g] 152 | let by = s[i] 153 | 154 | B = B &+ rotateLeft(x, by: by) 155 | A = dTemp 156 | } 157 | 158 | a0 = a0 &+ A 159 | b0 = b0 &+ B 160 | c0 = c0 &+ C 161 | d0 = d0 &+ D 162 | } 163 | 164 | assert(a0 >= 0) 165 | assert(b0 >= 0) 166 | assert(c0 >= 0) 167 | assert(d0 >= 0) 168 | 169 | let digest0: Byte = Byte((a0 >> 0) & 0xFF) 170 | let digest1: Byte = Byte((a0 >> 8) & 0xFF) 171 | let digest2: Byte = Byte((a0 >> 16) & 0xFF) 172 | let digest3: Byte = Byte((a0 >> 24) & 0xFF) 173 | 174 | let digest4: Byte = Byte((b0 >> 0) & 0xFF) 175 | let digest5: Byte = Byte((b0 >> 8) & 0xFF) 176 | let digest6: Byte = Byte((b0 >> 16) & 0xFF) 177 | let digest7: Byte = Byte((b0 >> 24) & 0xFF) 178 | 179 | let digest8: Byte = Byte((c0 >> 0) & 0xFF) 180 | let digest9: Byte = Byte((c0 >> 8) & 0xFF) 181 | let digest10: Byte = Byte((c0 >> 16) & 0xFF) 182 | let digest11: Byte = Byte((c0 >> 24) & 0xFF) 183 | 184 | let digest12: Byte = Byte((d0 >> 0) & 0xFF) 185 | let digest13: Byte = Byte((d0 >> 8) & 0xFF) 186 | let digest14: Byte = Byte((d0 >> 16) & 0xFF) 187 | let digest15: Byte = Byte((d0 >> 24) & 0xFF) 188 | 189 | let digest = [ 190 | digest0, digest1, digest2, digest3, digest4, digest5, digest6, digest7, 191 | digest8, digest9, digest10, digest11, digest12, digest13, digest14, digest15, 192 | ] 193 | 194 | assert(digest.count == 16) 195 | 196 | return Digest(digest) 197 | } 198 | 199 | // MARK: - Encoding a MD5 digest of bytes to a string 200 | public func encodeMD5(digest: [Byte]) -> String { 201 | assert(digest.count == 16) 202 | 203 | let str = digest.reduce("") { str, byte in 204 | let radix = 16 205 | let s = String(byte, radix: radix) 206 | // Ensure byte values less than 16 are padding with a leading 0 207 | let sum = str + (byte < Byte(radix) ? "0" : "") + s 208 | return sum 209 | } 210 | 211 | return str 212 | } 213 | 214 | // MARK: - String extension 215 | extension String { 216 | public var md5: String { 217 | return encodeMD5(digest: md5Digest) 218 | } 219 | 220 | public var md5Digest: [Byte] { 221 | let bytes = [Byte](self.utf8) 222 | let digest = calculateMD5(bytes) 223 | return digest.digest 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------