Swift Firebase存储如何检索未知名称的图像(NSUUID)

时间:2016-08-13 23:10:41

标签: swift firebase firebase-storage

我正在创建一个函数来检索url作为用户Image。但是,我的上传图片名称功能是由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 / - < -file name-> -

上传功能

  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")

  }

}

2 个答案:

答案 0 :(得分:3)

我强烈建议您同时使用Firebase存储和Firebase实时数据库来存储该UUID - > URL映射,以及" list"文件。 Realtime Database will handle offline use cases也像核心数据一样,所以没有理由使用核心数据或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及其associated source code,了解如何执行此操作的实际示例。

答案 1 :(得分:1)

有两种方法可以解决这个问题: -

1。)将用户profile_picture的Firebase存储路径存储在Firebase数据库中,并在每次开始下载个人资料照片之前检索。

2。)每次用户上传个人资料照片时,都会将文件路径存储在CoreData中,每次点击path以获取file_Path到存储该用户{{1}的位置}。

存储路径: -

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 ID,您可以使用USER SPECIFIC ID,如果您想要下载多个用户个人资料照片,您只需将currentUser放在适当位置即可。< / p>