In SwiftUI, you can allow the user to pick a video file from their photo library using the `UIImagePickerController`. Here's a step-by-step guide to achieve this:
1. **Import Required Modules**:
Ensure you import the necessary modules at the top of your SwiftUI view file.
```swift
import SwiftUI
import UIKit
```
2. **Create a SwiftUI View**:
Create a SwiftUI view where you will implement the video selection functionality.
```swift
struct VideoPickerView: View {
@State private var isShowingImagePicker = false
@State private var selectedVideo: URL?
var body: some View {
VStack {
if selectedVideo != nil {
VideoPlayer(player: AVPlayer(url: selectedVideo!))
.frame(height: 300)
} else {
Button("Select Video") {
isShowingImagePicker.toggle()
}
}
}
.sheet(isPresented: $isShowingImagePicker) {
ImagePicker(selectedImage: $selectedVideo, mediaType: .movie)
}
}
}
```
3. **Create an `ImagePicker` View**:
Create a separate `ImagePicker` SwiftUI view for selecting a video. This view uses `UIImagePickerController` behind the scenes.
```swift
struct ImagePicker: UIViewControllerRepresentable {
@Binding var selectedVideo: URL?
var mediaType: MediaType
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.mediaTypes = [mediaType.rawValue]
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
// Update
}
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let url = info[.mediaURL] as? URL {
parent.selectedVideo = url
}
picker.dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
}
}
}
```
4. **Define `MediaType` Enumeration**:
Define an enumeration to specify the media type you want to select. In this case, you'll select a movie (video).
```swift
enum MediaType: String {
case movie = "public.movie"
}
```
5. **Usage**:
You can use the `VideoPickerView` in your main SwiftUI content view or any other view where you want to allow the user to select a video.
```swift
struct ContentView: View {
var body: some View {
VideoPickerView()
}
}
```
This code sets up a SwiftUI view that allows the user to select a video from their photo library using `UIImagePickerController`. The selected video is displayed using a `VideoPlayer`.