Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

swift - 如何将图像上传到Firebase之类的Twitter应用程序?(How to upload images to firebase like twitter app?)

I have this View which shows a TextView to write some text and upload image.

(我有这个View ,它显示了一个TextView来编写一些文本并上传图像。)

The function postTweet below put the text with the user id into Firestore.

(下面的功能postTweet将带有用户ID的文本放入Firestore。)

But my problem is now, how to assign/upload an image to the firebase so that it can be identified, which user has uploaded the image too?

(但是现在我的问题是,如何将图像分配/上传到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 Method

(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")
                    }
                }
            }
    }
}
  ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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()
    }
}
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...