Skip to content

Instantly share code, notes, and snippets.

@itsanan
Last active June 22, 2020 17:46
Show Gist options
  • Save itsanan/adef885290a9633f90c89d848824edcc to your computer and use it in GitHub Desktop.
Save itsanan/adef885290a9633f90c89d848824edcc to your computer and use it in GitHub Desktop.
Four basic functions of persistent storage (CRUD) with URLSession.
//
// Services.swift
// PlayingAPI
//
// Created by Anantya F on 29/11/19.
// Copyright © 2019 Anantya F. All rights reserved.
//
import Foundation
class Services {
let api: String = "DROP YOUR API ENDPOINT HERE"
func getPengguna(completion: @escaping ([PenggunaModel]?) -> ()) {
guard let url = URL(string: api + "/api/users") else {
fatalError("Invalid URL")
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let pengguna = try? JSONDecoder().decode([PenggunaModel].self, from: data)
DispatchQueue.main.async {
completion(pengguna)
}
}.resume()
}
func createPengguna(name: String, id_roles: Int, email: String, password: String) {
UserDefaults.standard.removeObject(forKey: "receivedMessagePOSTPengguna")
guard let url = URL(string: api + "/api/users") else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let newData: [String: Any] = [
"name": name,
"id_roles": id_roles,
"email": email,
"password": password
]
let jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: newData, options: [])
request.httpBody = jsonData
} catch {
print("Error: cannot create JSON from data Users")
return
}
let session = URLSession.shared
let task = session.dataTask(with: request) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /api/users")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedData = try JSONSerialization.jsonObject(with: responseData,
options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The data is: " + receivedData.description)
UserDefaults.standard.set(receivedData.description, forKey: "receivedMessagePOSTPengguna")
} catch {
print("error parsing response from POST on /api/users")
return
}
}
task.resume()
}
func updatePengguna(id: Int, name: String, id_roles: Int, email: String, password: String) {
UserDefaults.standard.removeObject(forKey: "receivedMessagePUTMataPelajaran")
let id = String(id)
guard let url = URL(string: api + "/api/users/" + id) else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let newData: [String: Any] = [
"name": name,
"id_roles": id_roles,
"email": email,
"password": password
]
let jsonData: Data
do {
jsonData = try JSONSerialization.data(withJSONObject: newData, options: [])
request.httpBody = jsonData
} catch {
print("Error: cannot create JSON from data Pengguna")
return
}
let session = URLSession.shared
let task = session.dataTask(with: request) {
(data, response, error) in
guard error == nil else {
print("error calling PUT on /api/users")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedData = try JSONSerialization.jsonObject(with: responseData,
options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
UserDefaults.standard.set(receivedData.description, forKey: "receivedMessagePUTMataPelajaran")
print("The data is: " + receivedData.description)
} catch {
print("error parsing response from PUT on /api/users")
return
}
}
task.resume()
}
func deletePengguna(id: Int) {
UserDefaults.standard.removeObject(forKey: "receivedMessageDELETEPengguna")
let id = String(id)
guard let url = URL(string: api + "/api/users/" + id) else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
let session = URLSession.shared
let task = session.dataTask(with: request) {
(data, response, error) in
guard let _ = data else {
print("error calling DELETE on /api/users/" + id)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any]
else {
print("Could not get JSON from responseData as dictionary")
return
}
UserDefaults.standard.set(receivedData.description, forKey: "receivedMessageDELETEPengguna")
print("The data is: " + receivedData.description)
} catch {
print("error parsing response from DELETE on /api/pengguna")
return
}
}
task.resume()
}
}
@itsanan
Copy link
Author

itsanan commented Jan 2, 2020

Updated to Swift 5.1 💎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment