Last active
September 29, 2019 12:18
-
-
Save PetreVane/417b1d3bc0d6ffb91df4ae81603eb91f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ImageFetcher: Operation { | |
var photo: PhotoRecord | |
init(photo: PhotoRecord) { | |
self.photo = photo | |
} | |
override func main() { | |
if isCancelled { | |
return | |
} | |
guard let imageData = try? Data(contentsOf: photo.imageUrl) else { return } | |
if !imageData.isEmpty { | |
photo.image = UIImage(data: imageData) | |
photo.state = .downloaded | |
} else { | |
photo.image = UIImage(named: "Could not fetch image") | |
photo.state = .failed | |
print("Failed fetching image") | |
} | |
} | |
} | |
class PendingOperations { | |
lazy var downloadInProgress: [IndexPath: Operation] = [:] | |
lazy var downloadQueue: OperationQueue = { | |
var queue = OperationQueue() | |
queue.name = "Flickr fetching queue" | |
return queue | |
}() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func startDownload(for photoRecord: PhotoRecord, indexPath: IndexPath) { | |
guard pendingOperations.downloadInProgress[indexPath] == nil else { return } | |
let imageFetching = ImageFetcher(photo: photoRecord) | |
pendingOperations.downloadInProgress.updateValue(imageFetching, forKey: indexPath) | |
pendingOperations.downloadQueue.addOperation(imageFetching) | |
imageFetching.completionBlock = { | |
if imageFetching.isCancelled { | |
return | |
} | |
DispatchQueue.main.async { | |
self.tableView.reloadRows(at: [indexPath], with: .fade) | |
} | |
self.pendingOperations.downloadInProgress.removeValue(forKey: indexPath) | |
} | |
} | |
func suspendOperations() { | |
pendingOperations.downloadQueue.isSuspended = true | |
} | |
func resumeOperations() { | |
pendingOperations.downloadQueue.isSuspended = false | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum PhotoRecordState { | |
case new | |
case downloaded | |
case failed | |
} | |
class PhotoRecord { | |
let imageUrl: URL | |
var latitude: Double? | |
var longitude: Double? | |
var image = UIImage(named: "Flickr image") | |
var state = PhotoRecordState.new | |
let name: String | |
init(name: String, imageUrl: URL) { | |
self.name = name | |
self.imageUrl = imageUrl | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment