-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathApiCache.swift
More file actions
72 lines (62 loc) · 2 KB
/
ApiCache.swift
File metadata and controls
72 lines (62 loc) · 2 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
import Foundation
import WordPressAPI
import WordPressAPIInternal
import WordPressApiCache
extension WordPressApiCache {
static func bootstrap() -> WordPressApiCache? {
let instance: WordPressApiCache? = .onDiskCache() ?? .memoryCache()
instance?.startListeningForUpdates()
return instance
}
private static func onDiskCache() -> WordPressApiCache? {
let cacheURL: URL
do {
cacheURL = try FileManager.default
.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appending(path: "app.sqlite")
} catch {
NSLog("Failed to create api cache file: \(error)")
return nil
}
if let cache = WordPressApiCache.onDiskCache(file: cacheURL) {
return cache
}
if FileManager.default.fileExists(at: cacheURL) {
do {
try FileManager.default.removeItem(at: cacheURL)
if let cache = WordPressApiCache.onDiskCache(file: cacheURL) {
return cache
}
} catch {
NSLog("Failed to delete sqlite database: \(error)")
}
}
return nil
}
private static func onDiskCache(file: URL) -> WordPressApiCache? {
let cache: WordPressApiCache
do {
cache = try WordPressApiCache(url: file)
} catch {
NSLog("Failed to create an instance: \(error)")
return nil
}
do {
_ = try cache.performMigrations()
} catch {
NSLog("Failed to migrate database: \(error)")
return nil
}
return cache
}
private static func memoryCache() -> WordPressApiCache? {
do {
let cache = try WordPressApiCache()
_ = try cache.performMigrations()
return cache
} catch {
NSLog("Failed to create memory cache: \(error)")
return nil
}
}
}