-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.swift
More file actions
75 lines (61 loc) · 2.93 KB
/
API.swift
File metadata and controls
75 lines (61 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import Foundation
struct API {
static let baseURL = "http://localhost:3000"
static func register(username: String, password: String, completion: @escaping (Result<User, Error>) -> Void) {
// Implement registration API call
}
static func login(username: String, password: String, completion: @escaping (Result<User, Error>) -> Void) {
// Implement login API call
}
static func getUser(id: String, completion: @escaping (Result<User, Error>) -> Void) {
// Implement get user API call
}
static func transfer(from: String, to: String, amount: Double, completion: @escaping (Result<Void, Error>) -> Void) {
// Implement transfer API call
}
static func deposit(userId: String, amount: Double, completion: @escaping (Result<Void, Error>) -> Void) {
// Implement deposit API call
}
}
static func register(username: String, password: String, completion: @escaping (Result<User, Error>) -> Void) {
let url = URL(string: "\(baseURL)/register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = ["username": username, "password": password]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completion(.failure(NSError(domain: "Register Error", code: 0, userInfo: nil)))
return
}
do {
let user = try JSONDecoder().decode(User.self, from: data!)
completion(.success(user))
} catch {
completion(.failure(error))
}
}.resume()
}
static func login(username: String, password: String, completion: @escaping (Result<User, Error>) -> Void) {
let url = URL(string: "\(baseURL)/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = ["username": username, "password": password]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completion(.failure(NSError(domain: "Login Error", code: 0, userInfo: nil)))
return
}
do {
let user = try JSONDecoder().decode(User.self, from: