Skip to content

Instantly share code, notes, and snippets.

@Salman544
Last active March 20, 2019 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Salman544/b8f560b47afb02db32cdb43de6b7ea94 to your computer and use it in GitHub Desktop.
Save Salman544/b8f560b47afb02db32cdb43de6b7ea94 to your computer and use it in GitHub Desktop.
import Foundation
struct User: Codable {
let id: String?
let name: String
let email: String
let phoneNumber: String
let password: String
let status: String?
init(id: String? = nil,name: String, email: String, number: String, password: String) {
self.id = id
self.name = name
self.email = email
self.password = password
phoneNumber = number
self.status = nil
}
enum CodingKeys: String, CodingKey {
case id = "_id"
case name = "name"
case email = "email"
case phoneNumber = "phone_number"
case password = "password"
case status = "status"
}
}
struct ApiError: Decodable {
let message: String
}
class NetworkService {
enum NetworkError: Error {
case nodata
case jsonError(String)
case networkError(String)
case apiError(ApiError)
case none
}
static func fetchJson<T: Decodable>(with url: URL, completion: @escaping (T?, NetworkError) -> Void) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(nil, .networkError(error.localizedDescription))
return
}
var req = false
guard let data = data else {
completion(nil, .nodata)
return
}
if let response = response as? HTTPURLResponse {
if response.statusCode > 200 && response.statusCode > 308 {
req = true
}
}
do {
let decoder = JSONDecoder()
if req {
completion(nil, .apiError(try decoder.decode(ApiError.self, from: data)))
} else {
completion(try decoder.decode(T.self, from: data), .none)
}
} catch let jsonError {
completion(nil, NetworkError.jsonError(jsonError.localizedDescription))
}
}.resume()
}
}
let url = URL(string: "some url")!
NetworkService.fetchJson(with: url) { (user: User?, error) in
switch error {
case .nodata:
print("no data")
case .networkError(let err):
print(err)
case .jsonError(let err):
print(err)
case .apiError(let err):
print(err.message)
default:
guard let user = user else { return }
print(user)
}
}
print("hello world")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment