-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPIManager.swift
163 lines (136 loc) · 4.86 KB
/
APIManager.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//
// APIManager.swift
// Anibuddy
//
// Created by Kyle Grande.
//
protocol SettingsViewControllerDelegate: AnyObject {
func didChangeFetchType(to fetchTop: Bool)
}
import Foundation
import CoreData
class APIManager {
static let shared = APIManager()
private let baseURL = "https://api.jikan.moe/v4"
private init() {}
// Function to search anime based on a given query
func searchAnime(query: String, context: NSManagedObjectContext, completion: @escaping (Result<[Anime], Error>) -> Void) {
let encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let urlString = "\(baseURL)/anime?q=\(encodedQuery)&sfw=true&fields=mal_id,title,imageUrl,synopsis,type,episodes,score,startDate,endDate&page=1"
guard let url = URL(string: urlString) else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data"])))
return
}
// print("Printing data")
// print(String(data: data, encoding: .utf8)) // Print the response data
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let results = json?["data"] as? [[String: Any]] else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No results found"])))
return
}
let animes: [Anime] = results.compactMap { jsonAnime in
guard let anime = Anime.createFromJSON(jsonAnime, context: context) else { return nil }
return anime
}
context.performAndWait {
do {
try context.save()
} catch {
print("Error saving context: \(error.localizedDescription)")
}
}
completion(.success(animes))
} catch {
completion(.failure(error))
}
}.resume()
}
// Function to fetch top Anime from API
func fetchTopAnime(context: NSManagedObjectContext, completion: @escaping (Result<[Anime], Error>) -> Void) {
let urlString = "\(baseURL)/top/anime?limit=50&page=1"
guard let url = URL(string: urlString) else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data"])))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let results = json?["data"] as? [[String: Any]] else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No results found"])))
return
}
let animes: [Anime] = results.compactMap { jsonAnime in
guard let anime = Anime.createFromJSON(jsonAnime, context: context) else { return nil }
return anime
}
context.performAndWait {
do {
try context.save()
} catch {
print("Error saving context: \(error.localizedDescription)")
}
}
completion(.success(animes))
} catch {
completion(.failure(error))
}
}.resume()
}
// Function to fetch current season Anime from API
func fetchCurrentSeasonAnime(context: NSManagedObjectContext, completion: @escaping (Result<[Anime], Error>) -> Void) {
let urlString = "\(baseURL)/seasons/now"
guard let url = URL(string: urlString) else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data"])))
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let results = json?["data"] as? [[String: Any]] else {
completion(.failure(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No results found"])))
return
}
let animes: [Anime] = results.compactMap { jsonAnime in
guard let anime = Anime.createFromJSON(jsonAnime, context: context) else { return nil }
return anime
}
context.performAndWait {
do {
try context.save()
} catch {
print("Error saving context: \(error.localizedDescription)")
}
}
completion(.success(animes))
} catch {
completion(.failure(error))
}
}.resume()
}
}