Skip to content

Commit

Permalink
Changed PrefetchViewModel init with params to init()
Browse files Browse the repository at this point in the history
Use load(...) functions instead now.
  • Loading branch information
Sam-Spencer committed Apr 17, 2021
1 parent 72ad00b commit 61e78ba
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 13 deletions.
46 changes: 34 additions & 12 deletions Source/PrefetchImageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,60 @@ public final class PrefetchViewModel: ObservableObject, ScrollViewPrefetcherDele
private let scrollViewPrefetcer: ScrollViewPrefetcher
public private(set) var urls: [URL]

public init(photoURLs: [URL]) {
self.imagePrefetcher = ImagePrefetcher()
self.scrollViewPrefetcer = ScrollViewPrefetcher()
self.urls = photoURLs

self.scrollViewPrefetcer.delegate = self
public init() {
imagePrefetcher = ImagePrefetcher()
scrollViewPrefetcer = ScrollViewPrefetcher()
urls = []
scrollViewPrefetcer.delegate = self
}

public func load(photoURLs: [URL]) {
urls = photoURLs
scrollViewPrefetcer.scheduleRefreshIfNeeded()
}

public init(photoReferences: [StorageReference], uniqueURL: @escaping (StorageReference) -> URL?) {
self.imagePrefetcher = ImagePrefetcher()
self.scrollViewPrefetcer = ScrollViewPrefetcher()
self.urls = []
self.scrollViewPrefetcer.delegate = self
public func load(photoReferences: [StorageReference], uniqueURL: @escaping (StorageReference) -> URL?) {
let loadTask = DispatchGroup()
let totalRefs = photoReferences.count
var currentRef: Int = 1

for ref in photoReferences {
if currentRef == 1 {
loadTask.enter()
}

if let cachedURL = uniqueURL(ref) {
self.urls.append(cachedURL)
urls.append(cachedURL)

currentRef = currentRef + 1
if currentRef >= totalRefs {
loadTask.leave()
}
continue
} else {
DispatchQueue.global(qos: .userInitiated).async {
ref.downloadURL { (foundURL, thrownError) in
if let safeFoundURL = foundURL {
self.urls.append(safeFoundURL)
currentRef = currentRef + 1
} else {
if let safeError = thrownError {
print("[PrefetchViewModel] Unable to fetch download URL for photo. \(safeError)")
currentRef = currentRef + 1
}
}

if currentRef >= totalRefs {
loadTask.leave()
}
}
}
}
}

loadTask.notify(queue: DispatchQueue.main) {
self.scrollViewPrefetcer.scheduleRefreshIfNeeded()
}
}

func onAppear(_ index: Int) {
Expand Down
2 changes: 1 addition & 1 deletion Source/ScrollViewPrefetcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public final class ScrollViewPrefetcher {

/// SwiftUI sometimes calls onAppear in unexpected order, buffer takes care of it.
///
private func scheduleRefreshIfNeeded() {
internal func scheduleRefreshIfNeeded() {
guard !isRefreshScheduled else { return }
isRefreshScheduled = true
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { [weak self] in
Expand Down

0 comments on commit 61e78ba

Please sign in to comment.