ActivityView.swift
L Anyは任意の値を表すデータ型、どんな型でもOK
import SwiftUI
struct ActivityView: UIViewControllerRepresentable {
let shareItems: [Any]
func makeUIViewController(context: Context) ->
UIActivityViewController {
let controller = UIActivityViewController(
activityItems: shareItems,
applicationActivities: nil)
return controller
}
func uupdateUIViewController(
_ uiViewController: UIActivityViewController,
context: UIViewControllerRepresentableContext<ActivityView>){
}
}
ContentView.swift
L 写真がないこともある変数をオプショナル変数という アンラップ処理をする
Button(action: {
if let _ = captureImage{
isShowActivity = true
}
}){
Text("SNSに投稿する")
.frame(maxWidth: .infinity)
.frame(height: 50)
.multilineTextAlignment(.center)
.background(Color.blue)
.foregroundColor(Color.white)
}
.padding()
.sheet(isPresented: $isShowActivity){
ActivityView(shareItems: [captureImage!])
}
}
### フォトライブラリから写真を取り込めるようにする
PHPickerViewControllerはPhotoKitで提供されている機能
coordinatorを使用する
struct PHPickerView: UIViewControllerRepresentable {
@Binding var isShowSheet: Bool
@Binding var captureImage: UIImage?
class Coordinator: NSObject,
PHPickerViewControllerDelegate {
var parent: PHPickerView
init(parent: PHPickerView){
self.parent = parent
}
func picker(
_ picker: PHPickerViewController,
didFinishPicking results: [PHPickerResult]){
if let result = results.first {
result.itemProvider.loadObject(ofClass: UIImage.self){
(image, error) in
if let unwrapImage = image as? UIImage {
self.parent.captureImage = unwrapImage
} else {
print("使用できる写真がないです")
}
}
} else {
print("選択された写真はないです")
}
parent.isShowSheet = false
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
func makeUIViewController(
context:UIViewControllerRepresentableContext<PHPickerView>)
-> PHPickerViewController {
var configuration = PHPickerConfiguration()
configuration.filter = .images
configuration.selectionLimit = 1
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(
_ uiViewController: PHPickerViewController,
context: UIViewControllerRepresentableContext<PHPickerView>){
}
### カメラとフォトライブラリーの選択画面
.actionSheet(isPresented: $isShowAction){
ActionSheet(title: Text("確認"),
message: Text("選択してください"),
buttons: [
.default(Text("カメラ"), action: {
isPhotolibrary = false
if UIImagePickerController.isSourceTypeAvailable(.camera){
print("カメラは利用できます")
isShowSheet = true
} else {
print("カメラは利用できません")
}
}),
.default(Text("フォトライブラリー"), action: {
isPhotolibrary = true
isShowSheet = true
}),
.cancel()
])
}
なるほど、カメラを使えると中々面白い