TabManager.swift
2.86 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// DataBaseManager.swift
// browser
//
// Created by Artem Talko on 02.10.2023.
//
import Realm
import RealmSwift
import Alamofire
import UIKit
final class TabManager {
static let shared = TabManager()
private let realm: Realm
private init() {
do {
self.realm = try Realm()
} catch {
fatalError("Error initializing Realm: \(error.localizedDescription)")
}
}
func saveTabWithComplition(tabTitle: String, snapshotImage: UIImage?, tabUrl: String, completion: (Result<Void,Error>) -> Void) {
let newTab = BrowserTabDataBase(tabTitle: tabTitle, snapshotImage: snapshotImage, tabUrl: tabUrl)
do {
try realm.write {
realm.add(newTab)
completion(.success(()))
}
} catch {
print("Error adding new tab: \(error.localizedDescription)")
completion(.failure(error))
}
}
func saveTab(tabTitle: String, snapshotImage: UIImage?, tabUrl: String) {
let newTab = BrowserTabDataBase(tabTitle: tabTitle, snapshotImage: snapshotImage, tabUrl: tabUrl)
do {
try realm.write {
realm.add(newTab)
}
} catch {
print("Error adding new tab: \(error.localizedDescription)")
}
}
func updateTab(tabId: String, newTabTitle: String, newSnapshotImage: UIImage?, newTabUrl: String, completion: (Result<Void, Error>) -> Void) {
if let tabToUpdate = realm.object(ofType: BrowserTabDataBase.self, forPrimaryKey: tabId) {
do {
try realm.write {
tabToUpdate.tabTitle = newTabTitle
tabToUpdate.TabUrl = newTabUrl
if let image = newSnapshotImage {
tabToUpdate.snapshotImageData = image.pngData()
}
completion(.success(()))
}
} catch {
print("Error updating tab: \(error.localizedDescription)")
completion(.failure(error))
}
} else {
let error = NSError(domain: "Error", code: 404, userInfo: [NSLocalizedDescriptionKey: "Tab not found"])
completion(.failure(error))
}
}
func getAllTabs() -> [BrowserTabDataBase] {
let savedTabs = realm.objects(BrowserTabDataBase.self)
return Array(savedTabs)
}
func deleteTab(tabId: String) {
if let tabToDelete = realm.object(ofType: BrowserTabDataBase.self, forPrimaryKey: tabId) {
do {
try realm.write {
realm.delete(tabToDelete)
}
} catch {
print("Error deleting tab: \(error.localizedDescription)")
}
}
}
}