SHARE
TWEET

Untitled

a guest Mar 26th, 2020 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. final class Message: Decodable {
  2.     var id:Int?
  3.     var message: String
  4.     init(message:String){
  5.         self.message = message
  6.     }
  7. }
  8.  
  9.  
  10. import Foundation
  11. enum APIError:Error{
  12.     case responseProblem
  13.     case decodingProblem
  14.     case otherProblem
  15. }
  16.  
  17. struct APIRequest {
  18.     let resourceURL: URL
  19.  
  20.     init(endpoint: String){
  21.         let resourceString="fdgdfg"
  22.         guard let resourceURL = URL(string: resourceString) else {fatalError()}
  23.         self.resourceURL = resourceURL
  24.     }
  25.  
  26.     func save (_ messageToSave:Message, completion @escaping(Result<Message, APIError>) -> Void){
  27.  
  28.         do {
  29.             var urlRequest = UrlRequest(url: resourceURL)
  30.             urlRequest.httpMethod = "POST"
  31.             urlRequest.addValue("application/json",forHTTPHeaderFiled: "Content-Type")
  32.             urlRequest.httpBody = try JSONEncoder().ecode(messageToSave)
  33.  
  34.             let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
  35.                 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let jsonData = data else {
  36.                 completion(failure(.responseProblem))
  37.                 return
  38.                 }
  39.                
  40.                 do {
  41.                     let messageData = try HSONDecoder().decode(Message.self, from: jsonData)
  42.                     completion(.success(messageData))
  43.                 }catch{
  44.                     completion(.failure(.decodingProblem))
  45.                 }
  46.             }
  47.             dataTask.resume()
  48.         }catch{
  49.             completion(.failure(.encodingProblem))
  50.     }
  51. }
  52.  
  53. let message = Message(message: text)
  54. let postRequest = APIRequest(endpoint: "messages")
  55. postRequest.save(message,completion:{result in
  56. switch result {
  57. case .success(let message):
  58. printaaaa
  59. case .failure
  60. print bbbbb
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top