Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct XHR {
- enum Result<T> {
- case success(T)
- case failure(Error)
- }
- func urlSession<T>(method: String? = nil, file: String, data: Data? = nil, completionHandler: @escaping (Result<T>) -> Void) where T: Codable {
- let file = file.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
- // Set up the URL request
- guard let url = URL.init(string: file) else {
- print("Error: cannot create URL")
- return
- }
- var urlRequest = URLRequest(url: url)
- if method == "POST" {
- urlRequest.httpMethod = "POST";
- urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
- urlRequest.httpBody = data
- print(urlRequest.httpBody)
- }
- // set up the session
- let config = URLSessionConfiguration.default
- let session = URLSession(configuration: config)
- // vs let session = URLSession.shared
- // make the request
- let task = session.dataTask(with: urlRequest, completionHandler: {
- (data, response, error) in
- DispatchQueue.main.async { // Correct
- guard let responseData = data else {
- print("Error: did not receive data")
- return
- }
- let decoder = JSONDecoder()
- print(String(data: responseData, encoding: .utf8))
- do {
- let todo = try decoder.decode(T.self, from: responseData)
- completionHandler(.success(todo))
- } catch {
- print("error trying to convert data to JSON")
- //print(error)
- completionHandler(.failure(error))
- }
- }
- })
- task.resume()
- }
- }
- func login(username: String, password: String, completionHandler: @escaping (Login) -> Void) {
- let thing = User(username: username, password: password)
- let dataThing = User.archive(w: thing)
- xhr.urlSession(method: "POST", file: "https://kida.al/login_register/", data: dataThing) { (result: XHR.Result<User>) in
- switch result {
- case .failure(let error):
- completionHandler(.failure(error))
- case .success(let user):
- //let convertedThing = User.unarchive(d: user)
- completionHandler(.success(user))
- }
- }
- }
- videoViewModel.login(username: "rexhin", password: "bonbon") { (result: VideoViewModel.Login) in
- switch result {
- case .failure(let error):
- print("error")
- case .success(let user):
- print(user)
- }
- }
Add Comment
Please, Sign In to add comment