如何使用 Firebase 更新好友图像,如 whatsApp

How to update friends image like whatsApp with Firebase

我正在开发一个使用 Firebase 存储和实时数据库的聊天应用程序。 我的数据库中有一个 userFriends 树,每个用户都可以在其中获得他的朋友列表:

我存储了每个用户的个人资料照片,什么是最好的 way/logic 下载用户朋友的照片(使用 NSUrl 到本地文件/使用 NSData 在内存中/生成一个 URL) ,更重要的是,如果朋友修改了他的照片,要更新吗? 感谢您的帮助!

用于存储图像

参数

infoOnThePicture:- info 您从 UIImagePicker

发送的图片

completionBlock:- 上传完成时调用

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

    if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {
        print(referenceUrl)

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

        let asset = assets.firstObject
        print(asset)

        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
                         }
                          else{

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

                                print(metadata?.downloadURL())

                                print("The pic has been uploaded")

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

                                self.uploadSuccess(metadata!, storagePath: filePath)

                                completionBlock()
                    }

            })
        })

    }else{

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

    print(storagePath)

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

    NSUserDefaults.standardUserDefaults().synchronize()

}

用于检索图像

参数:-

UID:- userId

completion :- completionBlock 用于处理图像检索的完成

  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"
    print(filePath)
    print(filePath1)

    //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 {

        print(storagePath)

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


            }else{

                if let downloadedImage = UIImage(contentsOfFile: filePath1){

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

                    self.profilePicture = downloadedImage

                    completion(image : self.profilePicture)
            }
        }

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

关于检查你的朋友何时更改他们的个人资料图片,当用户更改其个人资料图片时,你将替换存储中的用户图片,并将其 link 存储在数据库中,并了解用户何时更改更改了其个人资料图片,使用 .observeEventType(.ChildChanged,.. 会通知您该位置的更改,然后通过 dispatch_

异步更新您的 UI

PS:- 请参考 Firebase 的官方示例,您正在此项目中寻找身份验证:https://github.com/firebase/quickstart-ios