-
Notifications
You must be signed in to change notification settings - Fork 5
/
APIs.swift
74 lines (56 loc) · 2.35 KB
/
APIs.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
//
// DataTaskHandler.swift
// Movie ticket booking app
//
// Created by Akash soni on 08/11/22.
//
import Foundation
struct Constants {
typealias movieListComplition = (_ :MovieData?) -> Void
typealias ratingComplition = (_ :Ratings?) -> Void
static let baseURL = "https://api.npoint.io/"
}
class APIs {
static func fetchApi(urlString: String, handler: @escaping Constants.movieListComplition) {
guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
request.httpMethod = "GET"
URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) { data, response, error in
if error == nil {
guard let data = data else { return }
let model = try? JSONDecoder().decode(MovieData.self, from: data)
handler(model)
}
}.resume()
}
static func fetchRatings(urlString: String, handler: @escaping Constants.ratingComplition) {
guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60.0)
request.httpMethod = "GET"
URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) { data, response, error in
if error == nil {
guard let data = data else { return }
let model = try? JSONDecoder().decode(Ratings.self, from: data)
handler(model)
}
}.resume()
}
}
/*
// how to use
private func fetchRatings() {
APIs.fetchRatings(urlString: Constants.baseURL + "3f07f86370e2f122234c") { ratings in
for i in 0 ..< self.movieList.count {
guard let ratings = ratings else { return }
let rating = ratings.filter({ rating in
return self.movieList[i].id == rating.id
}).first?.rating ?? 0.0
self.movieList[i].rating = String(format: "Rating: %.2f", rating)
self.movieList[i].ratingDouble = rating
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
*/