jerem jerem - 1 month ago 11x
Swift Question

How to update friends image like whatsApp with Firebase

Im working on a chat app using Firebase for storage and the realTime DB.
I have an userFriends tree in my DB where each user get his list of friends:

DB userFriend example

I have in storage each users profil photo , whats the best way/logic to download photos of the user's friends (to a local File with NSUrl/ in memory with NSData/ generate an URL) ,and more important to be updated if a friend modify his photo?
thanks for your help!


For storing the image


infoOnThePicture:- info of the picture that you send from the UIImagePicker

completionBlock:- call when the uploading is complete

func profilePictureUploading(infoOnThePicture : [String : AnyObject],completionBlock : (()->Void)) {

    if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {

        let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as! NSURL], options: nil)

        let asset = assets.firstObject

        asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (ContentEditingInput, infoOfThePicture)  in

            let imageFile = ContentEditingInput?.fullSizeImageURL
            print("imagefile : \(imageFile)")

            let filePath = FIRAuth.auth()!.currentUser!.uid +  "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))/\(imageFile!.lastPathComponent!)"
            //Creating a unique path for the image in FIRStorage

            print("filePath : \(filePath)")

           //Storing under the parent Node `ProfilePictures` in FIRStorage     FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: {

                    (metadata, error) in

                         if error != nil{

                            print("error in uploading image : \(error)")

                           //Show alert

                                print("metadata in : \(metadata!)")


                                print("The pic has been uploaded")

                                print("download url : \(metadata?.downloadURL())")

                                self.uploadSuccess(metadata!, storagePath: filePath)




            print("No reference URL found!")


//Storing the filepath to NSUserDefaults
 //Much better option would be to store the pictures filePath or storagePath in the FIREBASE DATABASE ITSELF WITH THE USERS DETAILS
 //And retrieve that storagePath every time you wanna download the image(much sound option)
 func uploadSuccess(metadata : FIRStorageMetadata , storagePath : String)
    print("upload succeded!")


    NSUserDefaults.standardUserDefaults().setObject(storagePath, forKey: "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)")



For retrieving the image

Parameters :-

UID:- userId

completion :- completionBlock for handling the completion for retrieval of your image

  func retrieveStorageForUID( UID : String, completion : ((image : UIImage) -> Void) ){
    print("initial storage")

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentDirectory = paths[0]
    let filePath = "file:\(documentDirectory)/\(UID).jpg"
    let filePath1 = "\(documentDirectory)/\(UID).jpg"

    //Again i am retrieving the storagePath from the NSUserDefaults but you can retrieve it from Firebase database if you stored it while uploading.
    if let storagePath = NSUserDefaults.standardUserDefaults().objectForKey("storagePath.\(UID)") as? String {


        FIRControllerClass.storageRef.child("ProfilePictures").child(storagePath).writeToFile(NSURL.init(string: filePath)!, completion: {(url, err) -> Void in

            if err != nil{

                self.delegate.firShowAlert("Error downloading", Message: "There was an error downloading your profile picture")


                if let downloadedImage = UIImage(contentsOfFile: filePath1){

                    print("DOWNLOADED IMAGE :\(downloadedImage)")

                    self.profilePicture = downloadedImage

                    completion(image : self.profilePicture)

    completion(image: UIImage(named: "defaultProfilePic")!)
     //Default profile pic or Placeholder picture if there is no picture from the user...which you can also download from the FIRStorage..think

As for checking when your friends change their profile picture, you will replace users pic in the storage when user changes its profile pic, and store its link in the DB, and for knowing when did the user changed its profile pic, Use .observeEventType(.ChildChanged,.. which will notify you of the change at that location, and then update your UI asynchronously through dispatch_

PS:- Refer to the official sample example's of Firebase, You are looking for authentication in this project :