如何更新像WhatsApp与Firebase的朋友形象 [英] How to update friends image like whatsApp with Firebase

查看:182
本文介绍了如何更新像WhatsApp与Firebase的朋友形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在存储每个用户profil照片,最好的方式/逻辑下载用户的朋友的照片(NSUrl的本地文件/内存与NSData /生成一个URL ),更重要的是如果朋友修改他的照片更新?
感谢您的帮助! > 参数

infoOnThePicture: info 您从 UIImagePicker



completionBlock: - 上传完成时调用

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

如果让referenceUrl = infoOnThePicture [UIImagePickerControllerReferenceURL] {
print(referenceUrl)

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

让asset = assets.firstObject
print(资产)

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

let imageFile = ContentEditingInput?.fullSize ImageURL
print(imagefile:\(imageFile))

let filePath = FIRAuth.auth()!。currentUser!.uid +/\(Int(NSDate.timeIntervalSinceReferenceDate ()* 1000))/ \(imageFile!.lastPathComponent!)
//为FIRStorage中的图像创建唯一路径
$ b $ print(filePath:\(filePath) )


//在FIRStorage FIRControllerClass.storageRef.child(ProfilePictures)中存储父节点`ProfilePictures`。child(filePath).putFile(imageFile !,元数据:nil ,完成:{

(元数据,错误)在

如果错误!=无{

print(上传图片时出错:\ (error))

//显示警报
}
else {

print(metadata in:\(metadata!))

打印(元数据?.downloadURL())

打印(图片已上传)

打印(下载url:\(metadata?.downloadURL() ))

self.uploadSuccess(metadata !, storagePath:filePath)

completionBlock()
}

})


$ b $ print $ {
$ b $ print $ {




//将文件路径存储到NSUserDefaults
//更好的选择是将图片filePath或storagePath存储在FIREBASE DATABASE本身和用户的详细信息中
//然后检索该存储路径你需要下载图像(很多声音选项)
func uploadSuccess(元数据:FIRStorageMetadata,storagePath:String)
{
print(upload succeded!)

打印(storagePa ()()()()()()
$ b NSUserDefaults.standardUserDefaults()。setObject(storagePath,forKey:storagePath.\((FIRAuth.auth()?. currentUser?.uid)!))

NSUserDefaults.standardUserDefaults()。synchronize()






> UID: - userId



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

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

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

//同样,我从NSUserDefaults中检索存储路径,但如果您在上传时存储它,则可以从Firebase数据库检索它。
如果让storagePath = NSUserDefaults.standardUserDefaults()。objectForKey(storagePath.\(UID))?字符串{

print(storagePath)

FIRControllerClass.storageRef.child(ProfilePictures)。child(storagePath).writeToFile(NSURL.init(string:filePath)!,完成:{(url,err) - >无效


如果err!= nil {


self.delegate.firShowAlert(下载错误,消息:下载你的个人资料图片时出错)


} else {

如果让downloadImage = UIImage(contentsOfFile:filePath1) {
$ b $ print(DOWNLOADED IMAGE:\(downloadedImage))

self.profilePicture = downloadedImage

完成(image:self.profilePicture )



$ b $ else
完成(image:UIImage(named:defaultProfilePic)!)
//默认的个人资料图片或占位符图片,如果没有来自用户的图片...你也可以做的从FIRStorage中获取wnload


code
$ b

至于检查何时你的朋友改变他们的个人资料图片,当用户改变他的个人资料图片,并将其链接存储在数据库,并知道用户何时更改其个人资料图片,使用。 observeEventType(.ChildChanged,.. 它会通知您在该位置的变化,然后通过 dispatch _

异步更新您的UI。

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


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:

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

Parameters

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

}

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

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 :https://github.com/firebase/quickstart-ios

这篇关于如何更新像WhatsApp与Firebase的朋友形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆