I am trying to upload my post separately but my image and and video url is being uploaded together and when I try to upload my text separately it is not uploading. Im not understanding why is my text being canceled out and not being uploaded I tried catching errors but nothing is appearing what am I missing from this code that’s not allowing my post to be uploaded separately
When the image is uploaded the videourl is being filled but when the video is being uploaded the imageurl line is not being filled that how its suppose to be
import SwiftUI
import Firebase
import PhotosUI
import FirebaseFirestoreSwift
@MainActor
class UploadPostViewModel: ObservableObject {
@Published var didUploadPost = false
@Published var error: Error?
@Published var profileImage: Image?
@Published var text = ""
@Published var videos = [Video]()
@Published var selectedVideoURL: URL?
@Published var selectedImage: PhotosPickerItem? {
didSet { Task { await loadImage(fromItem: selectedImage)
Task { try await uploadVideo() }
}
}
}
init(){
Task { try await fetchVideos() }
}
private var uiImage: UIImage?
func uploadPost(caption: String) async throws {
guard let uid = Auth.auth().currentUser?.uid else { return }
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])
var imageUrl: String? = nil
do{
if let image = uiImage {
imageUrl = try await ImageUploader.uploadImage(image: image , type: .post)
}
let post = Post(ownerUid: uid, text: text, caption: caption, likes: 0, videoURL: videoUrl, replyCount: 23, imageUrl: imageUrl, timestamp: Timestamp())
try await PostService.uploadPost(post)
self.didUploadPost = true
}catch{
}
}
func loadImage(fromItem item: PhotosPickerItem?) async {
guard let item = item 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 uploadVideo() 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) })
}
}




