Guest User

Untitled

a guest
Feb 10th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. struct XHR {
  2.  
  3. enum Result<T> {
  4. case success(T)
  5. case failure(Error)
  6. }
  7.  
  8. func urlSession<T>(method: String? = nil, file: String, data: Data? = nil, completionHandler: @escaping (Result<T>) -> Void) where T: Codable {
  9.  
  10. let file = file.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
  11.  
  12. // Set up the URL request
  13. guard let url = URL.init(string: file) else {
  14. print("Error: cannot create URL")
  15. return
  16. }
  17.  
  18. var urlRequest = URLRequest(url: url)
  19.  
  20. if method == "POST" {
  21. urlRequest.httpMethod = "POST";
  22. urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  23. urlRequest.httpBody = data
  24. print(urlRequest.httpBody)
  25. }
  26.  
  27. // set up the session
  28. let config = URLSessionConfiguration.default
  29. let session = URLSession(configuration: config)
  30. // vs let session = URLSession.shared
  31.  
  32. // make the request
  33. let task = session.dataTask(with: urlRequest, completionHandler: {
  34. (data, response, error) in
  35.  
  36. DispatchQueue.main.async { // Correct
  37.  
  38. guard let responseData = data else {
  39. print("Error: did not receive data")
  40. return
  41. }
  42.  
  43. let decoder = JSONDecoder()
  44. print(String(data: responseData, encoding: .utf8))
  45. do {
  46. let todo = try decoder.decode(T.self, from: responseData)
  47. completionHandler(.success(todo))
  48. } catch {
  49. print("error trying to convert data to JSON")
  50. //print(error)
  51. completionHandler(.failure(error))
  52. }
  53. }
  54. })
  55. task.resume()
  56. }
  57.  
  58. }
  59.  
  60. func login(username: String, password: String, completionHandler: @escaping (Login) -> Void) {
  61. let thing = User(username: username, password: password)
  62. let dataThing = User.archive(w: thing)
  63.  
  64. xhr.urlSession(method: "POST", file: "https://kida.al/login_register/", data: dataThing) { (result: XHR.Result<User>) in
  65. switch result {
  66. case .failure(let error):
  67. completionHandler(.failure(error))
  68. case .success(let user):
  69. //let convertedThing = User.unarchive(d: user)
  70. completionHandler(.success(user))
  71. }
  72. }
  73. }
  74.  
  75. videoViewModel.login(username: "rexhin", password: "bonbon") { (result: VideoViewModel.Login) in
  76. switch result {
  77. case .failure(let error):
  78. print("error")
  79.  
  80. case .success(let user):
  81. print(user)
  82. }
  83. }
Add Comment
Please, Sign In to add comment