Skip to content

Instantly share code, notes, and snippets.

@shanev
Created January 22, 2018 22:11
Show Gist options
  • Save shanev/fbf07fc0e9ccbdaa6f7cea685a8306b3 to your computer and use it in GitHub Desktop.
Save shanev/fbf07fc0e9ccbdaa6f7cea685a8306b3 to your computer and use it in GitHub Desktop.
//
// LivePhotoUtil.swift
// Blink
//
// Created by Shane Vitarana on 6/2/17.
// Copyright © 2017 Blink. All rights reserved.
//
import Alamofire
import BlinkApi
import Photos
import ReactiveSwift
import Result
final class LivePhotoUtil {
let imageFileUrlProperty = MutableProperty<URL?>(nil)
let videoFileUrlProperty = MutableProperty<URL?>(nil)
let livePhotoComponents: Signal<(URL?, URL?), NoError>
init() {
livePhotoComponents = Property.combineLatest(imageFileUrlProperty, videoFileUrlProperty)
.signal
}
func build(imageFileUrl: URL, videoFileUrl: URL) -> SignalProducer<PHLivePhoto, ClientError> {
return SignalProducer { observer, _ in
PHLivePhoto.request(
withResourceFileURLs: [imageFileUrl, videoFileUrl],
placeholderImage: nil,
targetSize: .zero,
contentMode: .default) { livePhoto, _ in
guard let livePhoto = livePhoto else {
observer.send(error: .livePhoto)
return
}
observer.send(value: livePhoto)
}
}
}
func download(imageUrlString: String, videoUrlString: String) {
download(urlString: imageUrlString, fileExtension: "jpg")
.startWithResult { result in
if let url = result.value {
self.imageFileUrlProperty.value = url
}
}
download(urlString: videoUrlString, fileExtension: "mov")
.startWithResult { result in
if let url = result.value {
self.videoFileUrlProperty.value = url
}
}
}
}
private extension LivePhotoUtil {
func download(urlString: String, fileExtension: String) -> SignalProducer<URL, NoError> {
return SignalProducer { observer, _ in
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("\(UUID().uuidString).\(fileExtension)")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(urlString, to: destination)
.response { (response) in
if response.error == nil, let fileUrl = response.destinationURL {
observer.send(value: fileUrl)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment