【问题标题】:Passing data from firebase to textfield将数据从 firebase 传递到 textfield
【发布时间】:2021-12-14 18:36:39
【问题描述】:

我在使用文本字段时遇到了困难。我正在从 Firebase RTDB 获取用户数据,我想在配置文件视图中显示一些数据,其中包含用于编辑数据的文本字段。

我的用户数据:

struct UserData: Codable, Identifiable {

var email : String?
var name : String?
var firstname : String?
var lastname : String?
var type: String?
var uid: String?
var profileImageUrl : String?
var id : String?
var fcmToken2 : String?
var onboarding : Bool?
var phone : String?
}

带有文本字段的视图:

struct ProfileViewDemo: View {
@Binding var user : UserData

@State private var email: String = ""

var body: some View {

TextField("\(user.firstname!)", text: $email, onEditingChanged: { edit in
                            self.editing = edit
                        })

}
}

如何将 email var 预设为 user.email 的值?我尝试使用 .onAppear,但这会导致照片加载出现问题。有什么方法可以使用来自 UserData 的数据预设电子邮件变量?谢谢。

编辑(添加 ProfileView 代码)

struct ProfileViewDemo: View {

@ObservedObject var session : SessionStore
@Binding var user : UserData

@State private var number: String = ""
@Binding var email: String = "123"
@State private var editing = false
@State private var editing2 = false
@State private var editing3 = false
@State private var editing4 = false
@State var refresh: Bool = false


   @State private var image: UIImage?
   @State private var shouldPresentImagePicker = false
   @State private var shouldPresentActionScheet = false
   @State private var shouldPresentCamera = false

var body: some View {
    ScrollView{
        VStack{
            VStack{
                ZStack{
                    ZStack{
                        if(image == nil){
                        KFImage.url(URL(string: "\(user.profileImageUrl!)"))
                                .loadDiskFileSynchronously()
                                .cacheMemoryOnly()
                                .fade(duration: 0.25)
                            
                                .onProgress { receivedSize, totalSize in  }
                                .onSuccess { result in  }
                                .onFailure { error in }
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                
                                .clipShape(Circle())
                                
                                .overlay(Circle().stroke(Color(red: 50 / 255, green: 51 / 255, blue: 53 / 255), lineWidth: 2))
                                
                                
                                .frame(width: 140, height: 140)
                        }
                        if (image != nil) {
                            Image(uiImage: image!)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                
                                .clipShape(Circle())
                                
                                .overlay(Circle().stroke(Color(red: 50 / 255, green: 51 / 255, blue: 53 / 255), lineWidth: 2))
                                
                                
                                .frame(width: 140, height: 140)
                        }

                    }
                    ZStack{
                        Button {
                            self.shouldPresentActionScheet = true
                        } label: {
                            Image(systemName: "camera")
                                .font(.system(size: 12))
                                .padding(.all, 5)
                                .background(Color(red: 50 / 255, green: 51 / 255, blue: 53 / 255))
                                .foregroundColor(Color.white)
                                .clipShape(Circle())
                        }
                        .sheet(isPresented: $shouldPresentImagePicker) {
                                        SUImagePickerView(sourceType: self.shouldPresentCamera ? .camera : .photoLibrary, image: self.$image, isPresented: self.$shouldPresentImagePicker)
                                }.actionSheet(isPresented: $shouldPresentActionScheet) { () -> ActionSheet in
                                    ActionSheet(title: Text("Choose mode"), message: Text("Please choose your preferred mode to set your profile image"), buttons: [ActionSheet.Button.default(Text("Camera"), action: {
                                        self.shouldPresentImagePicker = true
                                        self.shouldPresentCamera = true
                                    }), ActionSheet.Button.default(Text("Photo Library"), action: {
                                        self.shouldPresentImagePicker = true
                                        self.shouldPresentCamera = false
                                    }), ActionSheet.Button.cancel(Text("Atšaukti"))])
                                }
                        
                        
                    }
                    
                    .padding(.all, 3)
                    .background(Color.white)
                    .clipShape(Circle())
                    .offset(x: 50)
                    .offset(y: 50)
                }

            }
            .padding(.bottom, 15)

               
                ZStack {
                    ZStack(alignment: .leading){
                        ZStack(alignment: .leading){
                            
                            TextField("\(user.email!)", text: $email, onEditingChanged: { edit in
                                self.editing3 = edit
                            })
                                
                                
                                .padding(.leading, 5)
                                .padding(.trailing, 5)
                                .padding()
                                .offset(y: 0)
                        }.frame(maxWidth: .infinity, maxHeight: 50)
                            .overlay(
                                RoundedRectangle(cornerRadius: 5)
                                    .stroke(editing3 ? Color(UIColor.systemGray2) : Color(UIColor.systemGray5), lineWidth: 2)
                            )
                        
                            .background(Color(UIColor.white))
                            .cornerRadius(5)
                        
                        Text("El. Pašto adresas")
                            .disableAutocorrection(true)
                            .padding(.leading, 5)
                            .padding(.trailing, 5)
                            .background(Color.white)
                            .font(Font.custom("Montserrat-Regular", size: 15.0))
                            .foregroundColor(Color.gray)
                            .padding()
                            .offset(y: -25)
                    }
                    .frame(maxWidth: .infinity, maxHeight: 50) 
                }
            
                .padding(.bottom, 15)
        }

        .padding()
        .navigationBarItems(trailing:
                                Button("Išsaugoti") {
            
            print("Presed Profilio Informacija išsaugota!")
            updateProfileInfo()
            
            UIApplication.shared.endEditing()
        })
    }
    .onTapGesture {
       
        self.endTextEditing()
   
    }
}

func updateProfileInfo () {
    
    if (image != nil) {
        session.uplaodImage(image!) { (url) in
            if let url = url {
                session.updateProfileImage(url: url)
                print("Profile Image updated")
            }
        }
    }
    if (image == nil){
        print("Skipping image update - empty")
    }
    refresh.toggle()        
}
}

获取用户数据的代码:

func fetchUsers(){
    ref.child("users").observe(.childAdded) { (snapshot) in
        guard let dictionary = snapshot.value as? [String: AnyObject]  else { return}
            var user = UserData()
            
            user.email = (dictionary["email"] as! String)
            user.name = (dictionary["name"] as! String)
            user.firstname = (dictionary["firstname"] as! String)
            user.lastname = (dictionary["lastname"] as! String)
            user.type = (dictionary["type"] as! String)
            user.uid = (dictionary["uid"] as! String)
            user.profileImageUrl = (dictionary["profileImageUrl"] as! String)
            user.id = snapshot.key
            user.fcmToken2 = (dictionary["fcmToken"] as! String)
        user.phone = (dictionary["phone"] as! String)
            user.onboarding = (dictionary["onboarding"] as! Bool)
            
            self.users.append(user)
            
        }
}

【问题讨论】:

  • "我尝试使用 .onAppear,但这会导致照片加载出现问题。" ——展示你的尝试。目前尚不清楚“照片加载”是什么,因为你们的代码都没有处理照片。
  • 你所说的“火力基地”是什么人? Firebase 实时数据库?火库? Firebase 云消息传递? Firebase 存储?我们在您的代码行中哪里可以找到它?
  • @ElTomato 不要忘记 Firebase 身份验证,它似乎是。
  • @ElTomato 帖子指出我正在使用 RTDB(实时数据库)
  • @jnpdx 我用视图更新了帖子。我在 onTapGestue 之前有一个 .onAppear,它在 if(image == nil) 中显示了一个空白视图

标签: ios swift xcode firebase swiftui


【解决方案1】:

View 上使用 OnAppear 函数并分配值或从那里触发您的 API 调用。

struct ProfileViewDemo: View {
   @Binding var user : UserData
   @Binding var email: String = ""

   var body: some View {

     if email == "" {
         TextField("Enter email", text: $email)
     }
     else {
         TextField("", text: $email)
     }

   }.onAppear(perform: {
        email = user.email
        //You can fire your API call in here and assign the values
        }
  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多