Saturday, January 6, 2024
HomeiOS Developmentios - Tips on how to add particular paperwork to firestore

ios – Tips on how to add particular paperwork to firestore


I’m attempting to add my imageUrl to firestore however its being uploaded to firebase with a further area videoUrl being hooked up to it however I’m solely importing a picture and inside my imageUploader solely a Uiimage is classed not a video so why is my imageUrl put up being uploaded with a further area because the videoUrl and I did not add a video with the picture put up neither is it written that manner in my code. What’s unsuitable with my code and the way do I rewrite this code to add my picture to firestore with out the videoUrl area

class UploadPostViewModel: NSObject, ObservableObject {

  @Revealed var didUploadPost = false
  @Revealed var isLoading = false
  @Revealed var error: Error?
  @Revealed var movies = [Video]()
  @Revealed var mediaPreview: Film?
  @Revealed var profileImage: Picture?
  @Revealed var textual content = ""
  @Revealed var selectedImage: PhotosPickerItem? {
    didSet {
      Job { await loadImage(fromItem: selectedImage) }
      Job { attempt await uploadVideo() }
    }

  }
  personal var uiImage: UIImage?

  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 = attempt await objects?.loadTransferable(kind: Knowledge.self) {
      videoUrl = (attempt await VideoUploader.uploadVideo(withData: videoData))!
    }
    var imageUrl: String? = nil
    if let picture = uiImage {
      imageUrl = attempt await ImageUploader.uploadImage(picture: picture, kind: .put up)

      let put up = Submit(
        ownerUid: uid,
        textual content: textual content,
        videoUrl: videoUrl, likes: 0,
        replyCount: 23,
        imageUrl: imageUrl, timestamp: Timestamp()
      )

      attempt await PostService.uploadPost(put up)
      self.didUploadPost = true

    }

  }

  func loadImage(fromItem merchandise: PhotosPickerItem?) async {
    guard let merchandise = merchandise else { return }

    guard let knowledge = attempt? await merchandise.loadTransferable(kind: Knowledge.self) else { return }
    guard let uiImage = UIImage(knowledge: knowledge) else { return }
    self.uiImage = uiImage
    self.profileImage = Picture(uiImage: uiImage)
  }
  func uploadVideo() async throws {

    guard let objects = selectedImage else { return }
    guard let videoData = attempt await objects.loadTransferable(kind: Knowledge.self) else { return }
    guard let videoUrl = attempt await VideoUploader.uploadVideo(withData: videoData) else { return }
    attempt await Firestore.firestore().assortment("movies").doc().setData(["videoUrl": videoUrl])
  }
}
import Basis
import Firebase
import FirebaseStorage

enum UploadType {
    case profile
    case thread
    case message
    case put up
    
    var filePath: StorageReference {
        let filename = NSUUID().uuidString
        swap self {
        case .profile:
            return Storage.storage().reference(withPath: "/profile_images/(filename)")
        case .thread:
            return Storage.storage().reference(withPath: "/post_images/(filename)")
        case .message:
            return Storage.storage().reference(withPath: "/message_images/(filename)")
        case .put up:
            return Storage.storage().reference(withPath: "/post_images/(filename)")
        }
    }
}

struct ImageUploader {
    static func uploadImage(picture: UIImage, kind: UploadType) async throws -> String? {
        guard let imageData = picture.jpegData(compressionQuality: 0.5) else { return nil }
      
        let ref = kind.filePath
        
        do {
            let _ = attempt await ref.putDataAsync(imageData)
            let url = attempt await ref.downloadURL()
            return url.absoluteString
        } catch {
            print("DEBUG: Didn't add picture (error.localizedDescription)")
            return nil
        }
    }
}

Submit Service

  

  

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

    
    
   
           
        

    extension PostService {
        static func likePost(_ put up: Submit) async throws {
            guard let uid = Auth.auth().currentUser?.uid else { return }
            guard let postId = put up.id else { return }
            
            async let _ = attempt await FirestoreConstants.PostsCollection.doc(postId).assortment("post-likes").doc(uid).setData([:])
            async let _ = attempt await FirestoreConstants.PostsCollection.doc(postId).updateData(["likes": post.likes + 1])
            async let _ = attempt await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).setData([:])
            
           
        }
        
        static func unlikePost(_ put up: Submit) async throws {
            guard put up.likes > 0 else { return }
            guard let uid = Auth.auth().currentUser?.uid else { return }
            guard let postId = put up.id else { return }
            
            async let _ = attempt await FirestoreConstants.PostsCollection.doc(postId).assortment("post-likes").doc(uid).delete()
            async let _ = attempt await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).delete()
            async let _ = attempt await FirestoreConstants.PostsCollection.doc(postId).updateData(["likes": post.likes - 1])
            
           
        }
        
        static func checkIfUserLikedPost(_ put up: Submit) async throws -> Bool {
            guard let uid = Auth.auth().currentUser?.uid else { return false }
            guard let postId = put up.id else { return false }
            
            let snapshot = attempt await FirestoreConstants.UserCollection.doc(uid).assortment("user-likes").doc(postId).getDocument()
            return snapshot.exists
        }
    }
    
    // MARK: - Feed Updates
    
    extension PostService {
        personal static func updateUserFeedsAfterPost(postId: String) async throws {
            guard let uid = Auth.auth().currentUser?.uid else { return }
            
            let followersSnapshot = attempt await FirestoreConstants.FollowersCollection.doc(uid).assortment("user-followers").getDocuments()
            
            for doc in followersSnapshot.paperwork {
                attempt await FirestoreConstants
                    .UserCollection
                    .doc(doc.documentID)
                    .assortment("user-feed")
                    .doc(postId).setData([:])
            }
            
            attempt await FirestoreConstants.UserCollection.doc(uid).assortment("user-feed").doc(postId).setData([:])
        }
    }



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments