-
Notifications
You must be signed in to change notification settings - Fork 3
/
NetworkManager.swift
67 lines (55 loc) · 2.09 KB
/
NetworkManager.swift
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
import Combine
import SwiftUI
class NetworkManager: ObservableObject {
@Published var movies: [Movies] = []
var currentPage: Int = 1
@Published var sortby: String = "download_count"
@Published var category: String = ""
@Published var apiBaseURL: String
init(shouldLoadData: Bool) {
// Fetch the API base URL from UserDefaults or use a default value
self.apiBaseURL = UserDefaults.standard.string(forKey: "apiBaseURL") ?? "https://yts.mx/api/v2/"
if shouldLoadData {
self.loadData()
}
}
// MARK: - PAGINATION
func loadMoreContent(currentItem item: Movies) {
currentPage += 1
loadData()
}
// MARK: - API CALL
func loadData() {
let fullURLString = "\(apiBaseURL)/list_movies.json?genre=\(category)&sort_by=\(self.sortby)&limit=50&page=\(self.currentPage)"
guard let url = URL(string: fullURLString) else {
print("Invalid URL. Cannot load data.")
return
}
URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
guard let self = self else { return }
if let error = error {
print("Error fetching data: \(error.localizedDescription)")
return
}
guard let data = data else { return }
DispatchQueue.global(qos: .userInitiated).async {
do {
let result = try JSONDecoder().decode(ApiResponse.self, from: data)
DispatchQueue.main.async {
self.movies.append(contentsOf: result.data?.movies ?? [])
print("Page: \(self.currentPage)")
}
} catch {
print("Error parsing data: \(error.localizedDescription)")
}
}
}.resume()
}
func updateApiBaseURL(to newURL: String) {
UserDefaults.standard.set(newURL, forKey: "apiBaseURL")
self.apiBaseURL = newURL
self.currentPage = 1
self.movies.removeAll()
loadData()
}
}