Swift Firebase 存储如何检索名称未知的图像 (NSUUID)
Swift Firebase Storage How to retrieve image with unknow name(NSUUID)
我正在创建一个函数来检索 url 作为用户图像。但是,我的上传图片名称功能是由NSUUID 创建的。因此,我不知道每个用户个人资料图片的名称是什么。我如何改进我的代码以获得每个用户的用户 imgae 而不是硬编码 img 名称?
func getUserProfilePic(){
let uid = FIRAuth.auth()?.currentUser?.uid
let profilePath = refStorage.child("\(uid)").child("profilePic/xxxxx.jpg") // xxxxx = NSUUID
profilePath.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print("got no pic")
} else {
let profilePic: UIImage! = UIImage(data: data!)
self.imageV.image = profilePic
print("got pic")
}
}
}
路径为uid/profilePic/--<-文件名->--
上传功能
func uploadingPhoto(){
let uid = FIRAuth.auth()?.currentUser?.uid
let imgName = NSUUID().UUIDString + ".jpg"
let filePath = refStorage.child("\(uid!)/profilePic/\(imgName)")
var imageData = NSData()
imageData = UIImageJPEGRepresentation(profilePic.image!, 0.8)!
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
let uploadTask = filePath.putData(imageData, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
let downloadURL = metaData!.downloadURL()!.absoluteString
let uid = FIRAuth.auth()?.currentUser?.uid
let userRef = self.dataRef.child("user").child(uid!)
userRef.updateChildValues(["photoUrl": downloadURL])
print("alter the new profile pic and upload success")
}
}
有两种方法可以解决这个问题:-
1.) 将用户 profile_picture
的 Firebase 存储路径存储在您的 Firebase 数据库中,并在每次开始下载个人资料图片之前检索。
2.) 每次您的用户上传个人资料图片时,将文件路径存储在 CoreData
中,每次点击 path
以 file_Path 到您存储该用户的 profile_pic
.
存储路径:-
func uploadSuccess(metadata : FIRStorageMetadata , storagePath : String)
{
print("upload succeded!")
print(storagePath)
NSUserDefaults.standardUserDefaults().setObject(storagePath, forKey: "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)")
//Setting storagePath : (file path of your profile pic in firebase) to a unique key for every user "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)"
NSUserDefaults.standardUserDefaults().synchronize()
}
每次开始下载图片时,正在检索您的路径:-
let storagePathForProfilePic = NSUserDefaults.standardUserDefaults().objectForKey("storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)") as? String
注意:- 我正在使用 currentUser
ID,您可以使用 USER SPECIFIC id,如果您想下载多个用户的个人资料照片,您需要做的就是将他们的 uid
放在适当的位置.
我强烈建议同时使用 Firebase 存储和 Firebase 实时数据库来存储 UUID -> URL 映射,以及 "list" 文件。 Realtime Database will handle offline use cases 也喜欢 Core Data,所以真的没有理由迷恋 Core Data 或 NSUserDefaults
。下面是显示这些部分如何交互的一些代码:
已分享:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
上传:
let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
}
下载:
let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Do something with downloaded data...
})
})
有关详细信息,请参阅 Zero to App: Develop with Firebase, and it's associated source code,了解如何执行此操作的实际示例。
我正在创建一个函数来检索 url 作为用户图像。但是,我的上传图片名称功能是由NSUUID 创建的。因此,我不知道每个用户个人资料图片的名称是什么。我如何改进我的代码以获得每个用户的用户 imgae 而不是硬编码 img 名称?
func getUserProfilePic(){
let uid = FIRAuth.auth()?.currentUser?.uid
let profilePath = refStorage.child("\(uid)").child("profilePic/xxxxx.jpg") // xxxxx = NSUUID
profilePath.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
print("got no pic")
} else {
let profilePic: UIImage! = UIImage(data: data!)
self.imageV.image = profilePic
print("got pic")
}
}
}
路径为uid/profilePic/--<-文件名->--
上传功能
func uploadingPhoto(){
let uid = FIRAuth.auth()?.currentUser?.uid
let imgName = NSUUID().UUIDString + ".jpg"
let filePath = refStorage.child("\(uid!)/profilePic/\(imgName)")
var imageData = NSData()
imageData = UIImageJPEGRepresentation(profilePic.image!, 0.8)!
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
let uploadTask = filePath.putData(imageData, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
let downloadURL = metaData!.downloadURL()!.absoluteString
let uid = FIRAuth.auth()?.currentUser?.uid
let userRef = self.dataRef.child("user").child(uid!)
userRef.updateChildValues(["photoUrl": downloadURL])
print("alter the new profile pic and upload success")
}
}
有两种方法可以解决这个问题:-
1.) 将用户 profile_picture
的 Firebase 存储路径存储在您的 Firebase 数据库中,并在每次开始下载个人资料图片之前检索。
2.) 每次您的用户上传个人资料图片时,将文件路径存储在 CoreData
中,每次点击 path
以 file_Path 到您存储该用户的 profile_pic
.
存储路径:-
func uploadSuccess(metadata : FIRStorageMetadata , storagePath : String)
{
print("upload succeded!")
print(storagePath)
NSUserDefaults.standardUserDefaults().setObject(storagePath, forKey: "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)")
//Setting storagePath : (file path of your profile pic in firebase) to a unique key for every user "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)"
NSUserDefaults.standardUserDefaults().synchronize()
}
每次开始下载图片时,正在检索您的路径:-
let storagePathForProfilePic = NSUserDefaults.standardUserDefaults().objectForKey("storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)") as? String
注意:- 我正在使用 currentUser
ID,您可以使用 USER SPECIFIC id,如果您想下载多个用户的个人资料照片,您需要做的就是将他们的 uid
放在适当的位置.
我强烈建议同时使用 Firebase 存储和 Firebase 实时数据库来存储 UUID -> URL 映射,以及 "list" 文件。 Realtime Database will handle offline use cases 也喜欢 Core Data,所以真的没有理由迷恋 Core Data 或 NSUserDefaults
。下面是显示这些部分如何交互的一些代码:
已分享:
// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
上传:
let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
}
下载:
let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Do something with downloaded data...
})
})
有关详细信息,请参阅 Zero to App: Develop with Firebase, and it's associated source code,了解如何执行此操作的实际示例。