-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImagePicker.swift
68 lines (53 loc) · 1.91 KB
/
ImagePicker.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
// File.swift
//
//
// Created by Shunzhe Ma on 8/22/20.
//
/**
<key>NSPhotoLibraryUsageDescription</key>
<string>写真ライブラリへのアクセスが必要です</string>
*/
#if os(iOS) && !targetEnvironment(macCatalyst)
import Foundation
import UIKit
import SwiftUI
import MobileCoreServices
@available(iOS 13.0, *)
public struct ImagePicker: UIViewControllerRepresentable {
var onImagePicked: (UIImage) -> Void
var onCancelled: () -> Void
public init(onImagePicked: @escaping (UIImage) -> Void, onCancelled: @escaping () -> Void) {
self.onImagePicked = onImagePicked
self.onCancelled = onCancelled
}
public func makeCoordinator() -> Coordinator {
Coordinator(self)
}
public func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
return
}
public func makeUIViewController(context: Context) -> UIImagePickerController {
let pickerController = UIImagePickerController()
pickerController.delegate = context.coordinator
pickerController.mediaTypes = [kUTTypeImage as String]
pickerController.sourceType = .photoLibrary
return pickerController
}
public class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ vc: ImagePicker) {
self.parent = vc
super.init()
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let image = info[.originalImage] as? UIImage else {
self.parent.onCancelled()
return
}
self.parent.onImagePicked(image)
}
}
}
#endif