-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataManager.swift
95 lines (64 loc) · 2.13 KB
/
DataManager.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
//
// DataManager.swift
// RandomUser
//
// Created by Ayuna NYC on 1/9/17.
// Copyright © 2017 Ayuna NYC. All rights reserved.
//
import UIKit
enum UsersResult {
case success([User])
case failure(Error)
}
enum ImageResult {
case success(UIImage)
case failure(Error)
}
enum ApiError: Error {
case invalidJsonData
}
enum ImageError: Error {
case fetchImageError
}
struct DataManager {
let store = ImageStore()
func getUsers(completion: @escaping (UsersResult) -> Void) {
let file = Bundle.main.path(forResource: "randomUsers", ofType: "json")
let url = URL(fileURLWithPath: file!)
let data = try! Data(contentsOf: url, options: [])
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let dictArray = json["users"] as! [[String : Any]]
let users = dictArray.flatMap(User.userFromJsonDict)
if users.count > 0 {
completion(UsersResult.success(users))
} else {
completion(UsersResult.failure(ApiError.invalidJsonData))
}
}
func getImageForUser(user: User, completion: (ImageResult) -> Void) {
let image = store.retrieveLocalImageFor(user: user)
if image != nil {
user.avatar = image
completion(.success(image!))
} else {
let image = self.requestImageFromUrlFor(user: user)
if image != nil {
user.avatar = image
completion(.success(image!))
} else {
completion(.failure(ImageError.fetchImageError))
}
}
}
func requestImageFromUrlFor(user: User) -> UIImage? {
let data = try! Data(contentsOf: user.thumbnailUrl, options: [])
var image = UIImage()
if data.count > 0 {
image = UIImage(data: data)!
self.store.store(image: image, for: user)
return image
} else {
return nil
}
}
}