I'm新斯威夫特或者说整个编程世界和我正尝试学习如何在斯威夫特编程。我得到与包含由用户提供的不同的信息单元(VC1)的表图。我想点击一个细胞去通过赛格瑞一个新的VC。这种新的VC应该显示谁发布的信息的用户的用户信息。 I'm通过SEGUE传递用户ID从VC1 VC2来。在VC2我想下载使用用户ID的用户信息。
I'm使用的usermodel
import Foundation
class UserModel {
var username: String?
var email: String?
var profilImageUrl: String
var birthdayDate: String?
var gender: String?
init(dictionary: [String: Any]) {
username = dictionary["username"] as? String
email = dictionary["email"] as? String
profilImageUrl = dictionary["profilImageURL"] as? String ?? ""
birthdayDate = dictionary["Geburtsdatum"] as? String
gender = dictionary["gender"] as? String
}
}
路过的用户ID VC1 - > VC2的作品,我检查使用打印命令
我从VC2代码:
//MARK: - Outlets
@IBOutlet weak var nameLabel: UILabel!
//MARK: Var/ Let
var event: EventModel?
var users = [UserModel]()
var user: UserModel?{
didSet {
guard let _username = user?.username else {return}
nameLabel.text = _username
}
}
func loadUserDeatails(){
guard let userID = event?.uid else {return}
fetchUser(uid: userID)
}
func fetchUser(uid: String) {
let userRef = Database.database().reference().child("users").child(uid)
userRef.observeSingleEvent(of: .value) { (snapshot) in
guard let dic = snapshot.value as? [String: Any] else {return}
let newUser = UserModel(dictionary: dic)
self.users.append(newUser)
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadUserDeatails()
print(users)
}
所述nameLabel是空的以及阵列(用户),我试图在viewDidLoad中进行打印。 VAR“DIC”是包含用户的详细信息我下载了“后卫让用户ID =事件?.uid”所以我想这应该是正确的。希望有人能帮助我:)
我不知道什么event
正在做,但一个方法是:
在VC1:在prepareforsegue,一旦你VC2的参考,
let vc2 = segue.destination as! VC2
vc2.userId = "<USER_ID>" // Pass userId to VC2
在VC2:didSet
的var userId
会做的获取,然后分配用户名直接nameLabel.text
。
var userId: String? {
didSet {
// Do the fetch user details here
guard let userId = userId else {return}
let userRef = Database.database().reference().child("users").child(userID)
userRef.observeSingleEvent(of: .value) { (snapshot) in
guard let dic = snapshot.value as? [String: Any] else {return}
let newUser = UserModel(dictionary: dic)
// Once your get user detail data, set the label text
nameLabel.text = newUser["username"] ?? ""
}
}
}
请尝试以下,它可能工作。
var user: UserModel?{
didSet {
guard let _username = user?.username else {return}
guard let userID = event?.uid else {return}
let userRef = Database.database().reference().child("users").child(userID)
userRef.observeSingleEvent(of: .value) { (snapshot) in
guard let dic = snapshot.value as? [String: Any] else {return}
let newUser = UserModel(dictionary: dic)
nameLabel.text = newUser["username"] ?? ""
}
}
}