iOS Development

ios – Find out how to add a picture to firebase

Spread the love


I need assistance importing my picture to firebase, the code I’ve setup beneath permits my person to pick an image or a video from their photograph album utilizing photospickeritem however when the person choose a picture a video url is being uploaded with it as nicely and that permit my picture to be fetched with a videourl hooked up to it

I need to add my picture by itself with no video being hooked up as a result of when the video is uploaded a picture will not be hooked up to it How do I rewrite this code to add my picture by itself ?

import SwiftUI
import Firebase
import PhotosUI
import FirebaseStorage
import FirebaseFirestoreSwift

@MainActor
class UploadViewModel: NSObject, ObservableObject {
    
    
    
    @Revealed var didUploadPost = false
    @Revealed var isLoading = false
    @Revealed var error: Error?
    @Revealed var movies = [Video]()
    @Revealed var mediaPreview: Film?
    @Revealed var selectedVideoUrl: URL?
    @Revealed var profileImage: Picture?
    @Revealed var textual content = ""
    @Revealed var selectedImage: PhotosPickerItem? {
        didSet { Process { await uploadImage()
            
            Process { strive await postVideo() }
        }
            
        }
        
    }
    
    non-public var uiImage: UIImage?
    non-public var videoData: Information?
    func uploadPost(caption: String) async throws {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        
        var videoUrl: String? = nil
                   let objects = selectedImage
        if let videoData = strive await objects?.loadTransferable(kind: Information.self) {
            videoUrl = (strive await VideoUploader.uploadVideo(withData: videoData))!
            
            
        }
            
            
            var imageUrl: String? = nil
            if let picture = uiImage {
                imageUrl = strive await ImageUploader.uploadImage(picture: picture , kind: .publish)
            }
            
            let publish = Submit(
                ownerUid: uid,
                textual content: textual content,
                videoUrl: videoUrl, likes: 0,
                replyCount: 23,
                imageUrl: imageUrl, timestamp: Timestamp()
            )
            
            strive await PostService.uploadPost(publish)
            self.didUploadPost = true
            
            
            
        
        
        
    }
    
    func uploadImage() async {
        guard let merchandise = selectedImage else { return }
        
        guard let knowledge = strive? await merchandise.loadTransferable(kind: Information.self) else { return }
        guard let uiImage = UIImage(knowledge: knowledge) else { return }
        self.uiImage = uiImage
        self.profileImage = Picture(uiImage: uiImage)
    }
    func postVideo() async throws {
        guard let merchandise = selectedImage else {return}
        guard let videoData = strive await merchandise.loadTransferable(kind: Information.self) else {return}
        guard let videoUrl = strive await VideoUploader.uploadVideo(withData: videoData) else { return}
        strive await Firestore.firestore().assortment("movies").doc().setData(["videoUrl": videoUrl])
    }
    func fetchVideos() async throws {
        let snapshot = strive await Firestore.firestore().assortment("movies").getDocuments()
        self.movies = snapshot.paperwork.compactMap({ strive? $0.knowledge(as: Video.self) })
        }
    }


import Basis
import Firebase
import FirebaseFirestoreSwift

struct PostService {
    
    static func uploadPost(_ publish: Submit) async throws {
        guard let postData = strive? Firestore.Encoder().encode(publish) else { return }
        do{
        let ref = strive await FirestoreConstants.PostsCollection.addDocument(knowledge: postData)
        strive await updateUserFeedsAfterPost(postId: ref.documentID)
    } catch {
        print("---> (error)")
    }
    }
    
    static func fetchPost(withId id: String) async throws -> Submit {
        let postSnapshot = strive await FirestoreConstants.PostsCollection.doc(id).getDocument()
        let publish = strive postSnapshot.knowledge(as: Submit.self)
        return publish
    }
    
    static func fetchUserPosts(person: Userss) async throws -> [Post] {
        let snapshot = strive await FirestoreConstants.PostsCollection.whereField("ownerUid", isEqualTo: person.id).getDocuments()
        var posts = snapshot.paperwork.compactMap({strive? $0.knowledge(as: Submit.self )})
        
        for i in 0 ..< posts.depend {
            posts[i].person = person
        }
        
        return posts
    }
}

// MARK: - Likes

extension PostService {
    static func likePost(_ publish: Submit) async throws {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        guard let postId = publish.id else { return }
        
        async let _ = strive await FirestoreConstants.PostsCollection.doc(postId).assortment("post-likes").doc(uid).setData([:])
        async let _ = strive await FirestoreConstants.PostsCollection.doc(postId).updateData(["likes": post.likes + 1])
        async let _ = strive await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).setData([:])
        
       
    }
    
    static func unlikePost(_ publish: Submit) async throws {
        guard publish.likes > 0 else { return }
        guard let uid = Auth.auth().currentUser?.uid else { return }
        guard let postId = publish.id else { return }
        
        async let _ = strive await FirestoreConstants.PostsCollection.doc(postId).assortment("post-likes").doc(uid).delete()
        async let _ = strive await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).delete()
        async let _ = strive await FirestoreConstants.PostsCollection.doc(postId).updateData(["likes": post.likes - 1])
        
       
    }
    
    static func checkIfUserLikedPost(_ publish: Submit) async throws -> Bool {
        guard let uid = Auth.auth().currentUser?.uid else { return false }
        guard let postId = publish.id else { return false }
        
        let snapshot = strive await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).getDocument()
        return snapshot.exists
    }
}

// MARK: - Feed Updates

extension PostService {
    non-public static func updateUserFeedsAfterPost(postId: String) async throws {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        
        let followersSnapshot = strive await FirestoreConstants.FollowersCollection.doc(uid).assortment("user-followers").getDocuments()
        
        for doc in followersSnapshot.paperwork {
            strive await FirestoreConstants
                .UserCollection
                .doc(doc.documentID)
                .assortment("user-feed")
                .doc(postId).setData([:])
        }
        
        strive await FirestoreConstants.UserCollection.doc(uid).assortment("user-feed").doc(postId).setData([:])
    }
}

4 thoughts on “ios – Find out how to add a picture to firebase

  1. What i do not realize is in fact how you are no longer actually much more wellfavored than you might be right now Youre very intelligent You recognize thus considerably in relation to this topic made me in my view believe it from numerous numerous angles Its like men and women are not fascinated until it is one thing to do with Lady gaga Your own stuffs excellent All the time handle it up

  2. What i do not realize is in fact how you are no longer actually much more wellfavored than you might be right now Youre very intelligent You recognize thus considerably in relation to this topic made me in my view believe it from numerous numerous angles Its like men and women are not fascinated until it is one thing to do with Lady gaga Your own stuffs excellent All the time handle it up

Leave a Reply

Your email address will not be published. Required fields are marked *