如何像Twitter应用程序一样将图像上传到Firebase?

问题描述 投票:1回答:1

我有这个View,它显示了一个TextView,用于编写一些文本并上传图像。下面的函数postTweet将带有用户ID的文本放入Firestore。但是现在我的问题是,如何将图像分配/上载到firebase,以便可以识别它,哪个用户也已上载图像?

WriteTweet.Swift
import SwiftUI
import Firebase

struct ComposeView : View {
    @Binding var show : Bool
    @State var txt = ""
    @EnvironmentObject var session: SessionStore

    @Environment(\.editMode) var mode

    @State var isCancelled = false

    @State var showingPicker = false

    @State var image : Image? = nil
    var shortCut:String

    var body : some View{
        VStack{
            HStack{

                Button(action: {
                    self.image = nil
                    self.show.toggle()

                }) {

                    Text("Cancel")
                }
                Spacer()

                Button(action: {
                    self.showingPicker = true
                }) {

                    Image(systemName: "square.and.arrow.up").font(.largeTitle).foregroundColor(.blue)
                }
                Spacer()
                Button(action: {
                    postTweet(msg: self.txt, shortCut: self.shortCut)

                    self.show.toggle()

                }) {

                    Text("post").padding()

                }.background(Color("bg"))
                    .foregroundColor(.white)
                    .clipShape(Capsule())
            }

            multilineTextField(txt: $txt)
            Spacer()
            VStack(alignment: .leading, spacing: 5){
                HStack(alignment: .top, spacing: 5){


                    image?
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 200)
                        .clipShape(Circle())

                }.sheet(isPresented: $showingPicker,
                        onDismiss: {
                }, content: {
                    ImagePicker.shared.view
                })
                    .onReceive(ImagePicker.shared.$image) { image in
                        self.image = image

                }
            }
            Spacer()
        }.padding()
    }
}

PostTweet方法

func postTweet(msg : String,shortCut:String){

    let db = Firestore.firestore()
    guard let userId = Auth.auth().currentUser?.uid else { return }
    db.collection("users").whereField("uid", isEqualTo: userId)

        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    let name = document.get("firstname")
                    db.collection("tweets").document().setData(["name" : name as Any,"id":userId,"msg":msg,"groupsShortcut":shortCut,"retweet":"0","likes":"0","pic":"","url":" Image url "]) { (err) in

                        if err != nil{
                            print((err?.localizedDescription)!)
                            return
                        }

                        print("success")
                    }
                }
            }
    }
}
swift firebase google-cloud-firestore firebase-storage swiftui
1个回答
0
投票
class ShareService {

static var REF_STORAGE_POST = Storage.storage().reference().child("posts")

static func uploadDataToStorage(imageData: Data, postText: String, postDate: [AnyHashable: Any], onSuccess: @escaping () -> Void) {
    let imageId = NSUUID().uuidString
    let imageRef = REF_STORAGE_POST.child(imageId)

    imageRef.putData(imageData, metadata: nil) { (metadata, error) in
        if error != nil {
            return
        }

        imageRef.downloadURL(completion: { (url, error) in
            if error != nil {
                    return
                }
                    guard let imageUrl = url?.absoluteString else { return }
            self.uploadToDatabase(imageUrl: imageUrl, postText: postText, postDate: postDate, onSucces: onSuccess)
            })
    }
}

fileprivate static func uploadToDatabase(imageUrl: String, postText: String, postDate: [AnyHashable: Any], onSucces: @escaping () -> Void) {
    let newPostId = PostApi.shared.REF_POST.childByAutoId().key!
    let newPostRef = PostApi.shared.REF_POST.child(newPostId)

    guard let currentUserUid = UserApi.shared.CURRENT_USER_UID else { return }
    let dic = ["uid" : currentUserUid, "imageUrl" : imageUrl, "postText" : postText, "postDate" : postDate] as [String : Any]

    newPostRef.setValue(dic) { (error, _) in
        if error != nil {
            return
        }
        onSucces()
    }
}
 }
© www.soinside.com 2019 - 2024. All rights reserved.