SHARE
TWEET

Untitled

a guest Mar 26th, 2020 72 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. import Foundation
  8. enum APIError:Error{
  9.     case responseProblem
  10.     case decodingProblem
  11.     case otherProblem
  12. }
  13. struct APIRequest {
  14.     let resourceURL: URL
  15.  
  16.     init(endpoint: String){
  17.         let resourceString="fdgdfg"
  18.         guard let resourceURL = URL(string: resourceString) else {fatalError()}
  19.         self.resourceURL = resourceURL
  20.     }
  21.     func save (_ messageToSave:Message, completion @escaping(Result<Message, APIError>) -> Void){
  22.  
  23.         do {
  24.             var urlRequest = UrlRequest(url: resourceURL)
  25.             urlRequest.httpMethod = "POST"
  26.             urlRequest.addValue("application/json",forHTTPHeaderFiled: "Content-Type")
  27.             urlRequest.httpBody = try JSONEncoder().ecode(messageToSave)
  28.  
  29.             let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
  30.                 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, let jsonData = data else {
  31.                 completion(failure(.responseProblem))
  32.                 return
  33.                 }
  34.                 do {
  35.                     let messageData = try HSONDecoder().decode(Message.self, from: jsonData)
  36.                     completion(.success(messageData))
  37.                 }catch{
  38.                     completion(.failure(.decodingProblem))
  39.                 }
  40.             }
  41.             dataTask.resume()
  42.         }catch{
  43.             completion(.failure(.encodingProblem))
  44.     }
  45. }
  46. let message = Message(message: text)
  47. let postRequest = APIRequest(endpoint: "messages")
  48. postRequest.save(message,completion:{result in
  49. switch result {
  50. case .success(let message):
  51. printaaaa
  52. case .failure
  53. 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