Skip to content

Instantly share code, notes, and snippets.

@DDavis1025
Created June 14, 2020 23:02
Show Gist options
  • Save DDavis1025/6ccaeebf67037dbc3022f8b49012dc60 to your computer and use it in GitHub Desktop.
Save DDavis1025/6ccaeebf67037dbc3022f8b49012dc60 to your computer and use it in GitHub Desktop.
final class Comment: Codable {
var id:String?
var post_id:String?
var username:String?
var user_picture:String?
var user_id:String?
var text:String?
var parent_id:String?
init(post_id:String, username:String, user_picture:String, user_id:String, text:String, parent_id: String) {
self.post_id = post_id
self.username = username
self.user_picture = user_picture
self.user_id = user_id
self.text = text
self.parent_id = parent_id
}
}
struct CommentPostRequest {
let resourceURL:URL
init(endpoint:String) {
let resourceString = "http://localhost:8000/\(endpoint)"
guard let resourceURL = URL(string: resourceString) else {fatalError()}
self.resourceURL = resourceURL
}
func save(_ commentToSave: Comment, completion: @escaping(Result<Comment, APIError>) -> Void) {
do {
var urlRequest = URLRequest(url:resourceURL)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content_Type")
urlRequest.httpBody = try JSONEncoder().encode(commentToSave)
let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200,
let jsonData = data else {
completion(.failure(.responseProblem))
return
}
do {
let commentData = try JSONDecoder().decode(Comment.self, from: jsonData)
completion(.success(commentData))
} catch {
completion(.failure(.decodingProblem))
}
}
dataTask.resume()
} catch {
completion(.failure(.encodingProblem))
}
}
}
func performActionSend() {
if let text = textField.text,
let username = username,
let user_picture = profile?.picture,
let user_id = profile?.sub {
print("got info")
let comment = Comment(post_id: "", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text: text, parent_id: "")
let postRequest = CommentPostRequest(endpoint: "comment")
postRequest.save(comment) { (result) in
switch result {
case .success(let comment):
print("the following comment has been sent: \(comment)")
case .failure(let error):
print("An error occurred: \(error)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment