When my image is uploaded to firebase theres a extra field a videourl is added and that allows a video to be uploaded when the user image post is fetch from firebase but when the video is uploaded, it is uploaded by itself with no imageurl fields
I am stuck on this code i am not understanding why the videourl is being uploaded correctly to firebase but not the image. I want my user to be able to select a image or video from their photo album using photospickeritem to upload their post separately How can i fix this code to make that happen ?
class UploadPostViewModel: NSObject, ObservableObject {
@Published var didUploadPost = false
@Published var videos = [Video]()
@Published var profileImage: Image?
@Published var selectedImage: PhotosPickerItem? {
didSet { Task { await dataImage()
Task { try await sendVideo() }
}
}
}
private var uiImage: UIImage?
func uploadPost(caption: String) async throws {
guard let uid = Auth.auth().currentUser?.uid else { return }
var videoUrl: String? = nil
if let items = selectedImage {
let videoData = try await items.loadTransferable(type: Data.self)
videoUrl = (try await VideoUploader.uploadVideo(withData: videoData!))
}
var imageUrl: String? = nil
if let image = uiImage {
imageUrl = try await ImageUploader.uploadImage(image: image , type: .post)
}
let post = Post(
ownerUid: uid,
text: text,
videoUrl: videoUrl, likes: 0,
replyCount: 23,
imageUrl: imageUrl, timestamp: Timestamp()
)
try await PostService.uploadPost(post)
self.didUploadPost = true
}
func dataImage() async {
guard let item = selectedImage else { return }
guard let data = try? await item.loadTransferable(type: Data.self) else { return }
guard let uiImage = UIImage(data: data) else { return }
self.uiImage = uiImage
self.profileImage = Image(uiImage: uiImage)
}
func sendVideo() async throws {
guard let item = selectedImage else {return}
guard let videoData = try await item.loadTransferable(type: Data.self) else {return}
guard let videoUrl = try await VideoUploader.uploadVideo(withData: videoData) else { return}
try await Firestore.firestore().collection("videos").document().setData(["videoUrl": videoUrl])
}
func fetchVideos() async throws {
let snapshot = try await Firestore.firestore().collection("videos").getDocuments()
self.videos = snapshot.documents.compactMap({ try? $0.data(as: Video.self) })
}
}