Last active
August 27, 2017 15:54
-
-
Save sauravexodus/686f9db7244098fe630b33714d105ef5 to your computer and use it in GitHub Desktop.
An extension to Nuke for progressive image loading. [Required CocoaPods - RxNuke, RxSwift, FirebaseStorage]
This file contains hidden or 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
import RxNuke | |
import Nuke | |
import RxSwift | |
import Firebase | |
import RxCocoa | |
enum ImageVariants: String { | |
case high = "_high" | |
case med = "_med" | |
case low = "_low" | |
} | |
extension Manager { | |
func loadImage(with reference: String) -> Driver<Image> { | |
let variantLoaders: [Observable<Image>] = [ | |
FirebaseStorageReference.base | |
.child("\(reference)\(ImageVariants.low.rawValue)") | |
.rx | |
.downloadURL() | |
.flatMap({ (url) -> Observable<Image> in | |
return Nuke.Manager.shared.loadImage(with: url).orEmpty | |
}), | |
FirebaseStorageReference.base | |
.child("\(reference)\(ImageVariants.med.rawValue)") | |
.rx | |
.downloadURL() | |
.flatMap({ (url) -> Observable<Image> in | |
return Nuke.Manager.shared.loadImage(with: url).orEmpty | |
}), | |
FirebaseStorageReference.base | |
.child("\(reference)\(ImageVariants.high.rawValue)") | |
.rx | |
.downloadURL() | |
.flatMap({ (url) -> Observable<Image> in | |
return Nuke.Manager.shared.loadImage(with: url).orEmpty | |
}), | |
FirebaseStorageReference.base | |
.child(reference) | |
.rx | |
.downloadURL() | |
.flatMap({ (url) -> Observable<Image> in | |
return Nuke.Manager.shared.loadImage(with: url).orEmpty | |
}) | |
] | |
return Observable.concat(variantLoaders) | |
.shareReplay(1) | |
.asDriver( | |
//Load original image if no variants found | |
onErrorDriveWith: FirebaseStorageReference.base | |
.child(reference) | |
.rx | |
.downloadURL() | |
.flatMap({ (url) -> Observable<Image> in | |
return Nuke.Manager | |
.shared | |
.loadImage(with: url) | |
.orEmpty | |
}) | |
.asDriver { error in | |
// Return a default error image instead | |
return .just(Image(asset: .imageViewControllerError)) | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment