I am having issues uploading my image to firestore the image is uploading to firestore with a extra field listed as videoUrl with a emptyUrl attached to it and thats causing me problems when i go to fetch my image from firestore the image is being fetched with a video attached because there is a extra field in the document that i dont want to be there
How do i upload the image post with just the imageUrl attached into firestore and Why is a videoUrl being added to the image in firestore
I have tried catch errors and running breakpoints but i see nothing wrong what am i missing from this code that could cause this issue not allowing my code to be uploaded properly
class UploadPostViewModel: NSObject, ObservableObject {
@Published var didUploadPost = false
@Published var isLoading = false
@Published var error: Error?
@Published var videos = [Video]()
@Published var mediaPreview: Movie?
@Published var selectedVideoUrl: URL?
@Published var profileImage: Image?
@Published var text = ""
@Published var selectedImage: PhotosPickerItem? {
didSet { Task { await dataImage(fromItem: selectedImage)
Task { try await sendVideo() }
}
}
}
private var uiImage: UIImage?
func uploadPost(caption: String) async throws {
guard let uid = Auth.auth().currentUser?.uid else { return }
var imageUrl: String? = nil
if let image = uiImage {
do {
imageUrl = try await ImageUploader.uploadImage(image: image , type: .post)
var videoUrl: String? = nil
if let items = selectedImage {
let videoData = try await items.loadTransferable(type: Data.self)
videoUrl = (try await VideoUploader.uploadVideo(withData: videoData!))
}
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
} catch {
print("DEBUG: Failed to upload image with error \(error.localizedDescription)")
self.error = error
}
}
}
func dataImage(fromItem item: PhotosPickerItem?) 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) })
}
}
This is how i fetch and upload the user post to firestore
Full Code
import FirebaseFirestoreSwift
import Firebase
struct Post: Identifiable, Hashable, Codable {
@DocumentID var id: String?
let ownerUid: String
let text: String
var videoUrl: String!
var likes: Int
var replyCount: Int
let imageUrl: String?
let timestamp: Timestamp
var user: Userss?
var didLike: Bool? = false
}
import Firebase
struct FirestoreConstants {
private static let Root = Firestore.firestore()
static let UserCollection = Root.collection("users")
static let PostsCollection = Root.collection("posts")
static let ThreadsCollection = Root.collection("threads")
static let FollowersCollection = Root.collection("followers")
static let FollowingCollection = Root.collection("following")
static let RepliesCollection = Root.collection("replies")
static let ActivityCollection = Root.collection("activity")
static let MessagesCollection = Root.collection("messages")
}
import Foundation
import Firebase
import FirebaseFirestoreSwift
struct PostService {
static func uploadPost(_ post: Post) async throws {
guard let postData = try? Firestore.Encoder().encode(post) else { return }
do{
let ref = try await FirestoreConstants.PostsCollection.addDocument(data: postData)
try await updateUserFeedsAfterPost(postId: ref.documentID)
} catch {
print("---> \(error)")
}
}
static func fetchPost(withId id: String) async throws -> Post {
let postSnapshot = try await FirestoreConstants.PostsCollection.document(id).getDocument()
let post = try postSnapshot.data(as: Post.self)
return post
}
static func fetchUserPosts(user: Userss) async throws -> [Post] {
let snapshot = try await FirestoreConstants.PostsCollection.whereField("ownerUid", isEqualTo: user.id).getDocuments()
var posts = snapshot.documents.compactMap({try? $0.data(as: Post.self )})
for i in 0 ..< posts.count {
posts[i].user = user
}
return posts
}
}
// MARK: - Likes
extension PostService {
static func likePost(_ post: Post) async throws {
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let postId = post.id else { return }
async let _ = try await FirestoreConstants.PostsCollection.document(postId).collection("post-likes").document(uid).setData([:])
async let _ = try await FirestoreConstants.PostsCollection.document(postId).updateData(["likes": post.likes + 1])
async let _ = try await FirestoreConstants.UserCollection.document(uid).collection("user-likes").document(postId).setData([:])
}
static func unlikePost(_ post: Post) async throws {
guard post.likes > 0 else { return }
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let postId = post.id else { return }
async let _ = try await FirestoreConstants.PostsCollection.document(postId).collection("post-likes").document(uid).delete()
async let _ = try await FirestoreConstants.UserCollection.document(uid).collection("user-likes").document(postId).delete()
async let _ = try await FirestoreConstants.PostsCollection.document(postId).updateData(["likes": post.likes - 1])
}
static func checkIfUserLikedPost(_ post: Post) async throws -> Bool {
guard let uid = Auth.auth().currentUser?.uid else { return false }
guard let postId = post.id else { return false }
let snapshot = try await FirestoreConstants.UserCollection.document(uid).collection("user-likes").document(postId).getDocument()
return snapshot.exists
}
}
// MARK: - Feed Updates
extension PostService {
private static func updateUserFeedsAfterPost(postId: String) async throws {
guard let uid = Auth.auth().currentUser?.uid else { return }
let followersSnapshot = try await FirestoreConstants.FollowersCollection.document(uid).collection("user-followers").getDocuments()
for document in followersSnapshot.documents {
try await FirestoreConstants
.UserCollection
.document(document.documentID)
.collection("user-feed")
.document(postId).setData([:])
}
try await FirestoreConstants.UserCollection.document(uid).collection("user-feed").document(postId).setData([:])
}
}




