swift - 如何从用户 ID 中获取用户名和照片网址 - Swift 和 Firebase
问题描述
我有另一个 swift 文件,其中存储了 Firebase 中的所有当前用户信息,但由于某种原因它无法正常工作,看起来好像没有数据。如果有人可以帮助我找出我做错了什么,我将不胜感激。
class UserService {
static var currentUserProfile:UserProfile?
static func observeUserProfile(_ uid: String, completion: @escaping ((_ userProfile: UserProfile?)-> ()) ) {
let userRef = Database.database().reference().child("users/\(uid)")
userRef.observe(.value) { (snapshot) in
var userProfile:UserProfile?
if let dict = snapshot.value as? [String: Any],
let username = dict["username"] as? String,
let photoUrl = dict["photoUrl"] as? String,
let url = URL(string: photoUrl) {
userProfile = UserProfile(uid: snapshot.key, username: username, photoUrl: url)
}
completion(userProfile)
}
}
}
然后我使用用户名和 photoUrl 在我的 setValue 函数中使用它......
func sendDataToDatabaseFound(address: String, breed: String, phone: String, photoUrl: String, timestamp: String) {
//por the time being photoUrl:String - wasn't added because I can't get the downloadURL
// func sendDataToDatabase(address: String, breed: String, phone: String, lostfound: String, photoUrl: String)
var ref: DatabaseReference!
ref = Database.database().reference()
let postsReference = ref.child("posts").child("found")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
// Still need to add the "photo": photoUrl --> newPostReference.setValue(["photoUrl": photoUrl]
let toId = Auth.auth().currentUser?.uid
newPostReference.setValue( ["address": address, "breed": breed, "phone": phone,"photoUrl": photoUrl, "timestamp": timestamp, "author": ["userid": toId, "username": UserService.currentUserProfile?.username, "profilePhotoUrl": UserService.currentUserProfile?.photoUrl.absoluteString]]) { (error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
解决方案
如果您查看 的代码Auth.auth().currentUser
,您会发现它属于刚刚在 Swift 中FIRUser
调用的类。是 的子类,它具有许多特征,包括 providerID、uid、displayName、photoURL、email 和 phoneNumber。User
FIRUser
FIRUserInfo
您可以像访问uid
.currentUser
if let user = Auth.auth().currentUser {
let providerID: String = user.providerID
let uid: String = user.uid
let displayName: String = user.displayName
let photoURL: String = user.photoURL
let email: String = user.email
}
推荐阅读
- node.js - puppeteer 中的 page.$eval 函数总是返回 undefined
- php - 如何向不同的用户显示不同的 MySQL 结果?
- sql - 动态日期范围内的总和
- time - 我如何计算这个算法的时间复杂度?
- flask - 如何在 Flasgger 中注册 Swagger 端点
- openssl - 仅 OpenSSL 数字签名摘要
- typescript - 对象解构和转换
- ionic-framework - 为什么 Ionic 组件会渲染
然后在里面, , 而不是仅仅渲染 ? - javascript - 不能在纯 JS 中结合 setInterval() 和 if(confirm())
- c++ - 为什么使用 SPI 时全局缓冲区变量产生的结果与局部缓冲区变量不同?