一对一直播app开发,单次获得或上传一张相册里的照片实现的相关代码
SwiftUI没办法自己获取系统相册内容,所以得依靠一下UIKit,头文件如下:
import SwiftUI
import UIKit
首先我们创建一个ImagePicker结构体供我们获取系统相册内容:
struct ImagePicker: UIViewControllerRepresentable {
@Environment(\.presentationMode) private var presentationMode
let sourceType: UIImagePickerController.SourceType
let onImagePicked: (UIImage) -> Void
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding private var presentationMode: PresentationMode
private let sourceType: UIImagePickerController.SourceType
private let onImagePicked: (UIImage) -> Void
init(presentationMode: Binding<PresentationMode>,
sourceType: UIImagePickerController.SourceType,
onImagePicked: @escaping (UIImage) -> Void) {
_presentationMode = presentationMode
self.sourceType = sourceType
self.onImagePicked = onImagePicked
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
onImagePicked(uiImage)
presentationMode.dismiss()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
presentationMode.dismiss()
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(presentationMode: presentationMode,
sourceType: sourceType,
onImagePicked: onImagePicked)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.sourceType = sourceType
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController,
context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}
然后我们就可以很简单地从系统相册中获取照片了:
struct ContentView: View {
@State private var showImagePicker = false
//这里的image用于放置等会获取的照片
@State private var image: UIImage = UIImage()
var body: some View {
List{
Button(action: {
showImagePicker = true
}, label: {
Text("Select Image")
})
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
}
.sheet(isPresented: $showImagePicker,
content: {
ImagePicker(sourceType: .photoLibrary) { image in
self.image = image
}
})
}
}
以上就是一对一直播app开发,单次获得或上传一张相册里的照片实现的相关代码, 更多内容欢迎关注之后的文章