Last active
June 12, 2018 10:32
-
-
Save ezequieloliveiralima/07f3cbe2fa0823a2f6a86908882e02e6 to your computer and use it in GitHub Desktop.
Http Requests sample
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 | |
| enum Http { | |
| typealias Callback = (Response) -> Void | |
| enum Response { | |
| case success(data: Any?) | |
| case error(message: String?) | |
| } | |
| private struct Method { | |
| static let get = "GET" | |
| static let post = "POST" | |
| } | |
| case signIn(email: String, password: String) | |
| var method: String { | |
| switch self { | |
| case .signIn: return Method.post | |
| } | |
| } | |
| var uri: String { | |
| switch self { | |
| case .signIn: return "sign-in" | |
| } | |
| } | |
| var body: String? { | |
| switch self { | |
| case let .signIn(email, password): return "email=\(email)&password=\(password)" | |
| } | |
| } | |
| func request(_ callback: Callback?) { | |
| let url = URL(string: "https://example.com/api/\(uri)") | |
| URLSession.shared.invalidateAndCancel() | |
| var request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 30.0) | |
| request.httpMethod = method | |
| request.httpBody = body?.data(using: String.Encoding.utf8) | |
| URLSession.shared.dataTask(with: request) { (data, urlResponse, error) in | |
| guard error == nil else { | |
| callback?(.error(message: error!.localizedDescription)) | |
| return | |
| } | |
| callback?(.success(data: data)) | |
| } | |
| .resume() | |
| } | |
| } | |
| Http.signIn(email: "root@default", password: "toor") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment