如何使用Firebase更新whatsApp等朋友图片

时间:2016-09-03 21:21:36

标签: swift firebase-realtime-database firebase-storage

我正在使用Firebase存储和realTime数据库处理聊天应用。 我的数据库中有一个userFriends树,每个用户都可以获得他的朋友列表:

DB userFriend example

我有存储每个用户profil照片,有什么最好的方式/逻辑来下载用户朋友的照片(使用NSUrl /在内存中使用NSData /生成URL的本地文件),更重要的是如果朋友修改他的照片要更新? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

用于存储图像

<强>参数

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

完成: - 用于处理图像检索完成的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
    }
}

至于检查朋友何时更改其个人资料图片时,您将在用户更改其个人资料图片时替换存储中的用户图片,并将其链接存储在数据库中,并了解用户何时更改其个人资料图片,使用.observeEventType(.ChildChanged,..会通知您该位置的更改,然后通过dispatch_异步更新您的用户界面

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