Skip to content

Instantly share code, notes, and snippets.

@kkk669
Created Jul 29, 2021
Embed
What would you like to do?
https://zenn.dev/harumaru/articles/6f7ec2659261f6 の記事の LivePhotoView を Swift Playgrounds で表示するサンプルコード
import PhotosUI
import PlaygroundSupport
import SwiftUI
struct LivePhotoView: View {
let livePhoto: PHLivePhoto
var body: some View {
_LivePhotoView(livePhoto: livePhoto)
.aspectRatio(
livePhoto.size.width / livePhoto.size.height,
contentMode: .fill
)
}
}
fileprivate struct _LivePhotoView: UIViewRepresentable {
let livePhoto: PHLivePhoto
func makeUIView(context: Context) -> PHLivePhotoView {
let livePhotoView = PHLivePhotoView(frame: .zero)
livePhotoView.livePhoto = livePhoto
return livePhotoView
}
func updateUIView(_ livePhotoView: PHLivePhotoView, context: Context) {
}
}
struct PhotoPicker {
let configuration: PHPickerConfiguration
@Binding var pickerResult: [PHLivePhoto]
@Binding var isPresented: Bool
}
extension PhotoPicker: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> PHPickerViewController {
let controller = PHPickerViewController(configuration: configuration)
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(
pickerResult: self.$pickerResult,
isPresented: self.$isPresented
)
}
}
class Coordinator: PHPickerViewControllerDelegate {
@Binding var pickerResult: [PHLivePhoto]
@Binding var isPresented: Bool
init(
pickerResult: Binding<[PHLivePhoto]>,
isPresented: Binding<Bool>
) {
self._pickerResult = pickerResult
self._isPresented = isPresented
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
for image in results {
if image.itemProvider.canLoadObject(ofClass: PHLivePhoto.self) {
image.itemProvider.loadObject(ofClass: PHLivePhoto.self) { newImage, error in
if let error = error {
print(error.localizedDescription)
} else {
self.pickerResult.append(newImage as! PHLivePhoto)
}
}
} else {
print("Loaded Assest is not a Image")
}
}
// dissmiss the picker
self.isPresented = false
}
}
struct ContentView {
@State var isPresented = false
@State var pickerResult = [PHLivePhoto]()
var config: PHPickerConfiguration {
var config = PHPickerConfiguration(photoLibrary: .shared())
config.filter = .livePhotos
config.selectionLimit = 1
return config
}
}
extension ContentView: View {
var body: some View {
VStack {
if let livePhoto = self.pickerResult.first {
// どちらも潰れてない
LivePhotoView(livePhoto: livePhoto)
_LivePhotoView(livePhoto: livePhoto)
}
Button("Select Photo") {
self.isPresented = true
}
.sheet(isPresented: self.$isPresented) {
PhotoPicker(
configuration: self.config,
pickerResult: self.$pickerResult,
isPresented: self.$isPresented
)
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment