Last active
May 13, 2016 00:23
-
-
Save soffes/b6716b3f7e8f1ccd8536a4237d99d57a to your computer and use it in GitHub Desktop.
Simple Imgix client in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| // From https://github.com/soffes/Crypto | |
| import Crypto | |
| struct Imgix { | |
| // MARK: - Properties | |
| let host: String | |
| let secret: String | |
| let defaultParameters: [NSURLQueryItem]? | |
| // MARK: - Initializers | |
| init(host: String, secret: String, defaultParameters: [NSURLQueryItem]? = nil) { | |
| self.host = host | |
| self.secret = secret | |
| self.defaultParameters = defaultParameters | |
| } | |
| // MARK: - Building URLs | |
| func signPath(input: String) -> NSURL? { | |
| // Get components | |
| let path = (input.hasPrefix("/") ? "" : "/") + input | |
| guard let components = NSURLComponents(string: "https://\(host + path)") else { return nil } | |
| // Apply default query items | |
| var queryItems = components.queryItems ?? [] | |
| if let defaultParameters = defaultParameters where !defaultParameters.isEmpty { | |
| queryItems += defaultParameters | |
| components.queryItems = queryItems | |
| } | |
| // Calculate signature | |
| var base = secret + path | |
| if let query = components.query where !query.isEmpty { | |
| base += "?\(query)" | |
| } | |
| guard let signature = base.MD5 else { return nil } | |
| // Apply signature | |
| queryItems.append(NSURLQueryItem(name: "s", value: signature)) | |
| components.queryItems = queryItems | |
| // Return signed URL | |
| return components.URL | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment