Nicholas Agger Lui
Nicholas Agger Lui

Reputation: 729

Swift Firebase Storage How to retrieve image with unknow name(NSUUID)

I am making a function to retrieve the url as the user Image. However, my upload image name function created by NSUUID. Therefore, I would not know what is the name of each user profile picture. How could I improve my code to get the user imgae for every user instead of hard coding the img name?

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

The path is uid/profilePic/--<-file name->--

upload function

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

  }

}

Upvotes: 1

Views: 1236

Answers (2)

Mike McDonald
Mike McDonald

Reputation: 15953

I highly recommend using Firebase Storage and the Firebase Realtime Database together to store that UUID -> URL mapping, and to "list" files. The Realtime Database will handle offline use cases like Core Data as well, so there's really no reason to futz with Core Data or NSUserDefaults. Some code to show how these pieces interact is below:

Shared:

// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()

Upload:

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

Download:

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...
  })
})

For more information, see Zero to App: Develop with Firebase, and it's associated source code, for a practical example of how to do this.

Upvotes: 3

Dravidian
Dravidian

Reputation: 9945

There can be two ways to go about this :-

1.) Store the Firebase Storage path of users profile_picture in your Firebase database and retrieve every time before you start downloading your profile picture.

2.) Store the file path in CoreData every time your user uploads a profile picture and hit that path every time to get file_Path to where you stored that user's profile_pic .

Storing the path :-

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

 }

Retrieving your path, Every time you start downloading your image :-

let storagePathForProfilePic = NSUserDefaults.standardUserDefaults().objectForKey("storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)") as? String

Note :- i am using currentUser ID, you can use USER SPECIFIC id ,if you want to download multiple users profile pics, all you need to do is put their uid in place.

Upvotes: 1

Related Questions