将UIImage Picker中的图像上传到新的Firebase(Swift) [英] Uploading Images from UIImage Picker onto new Firebase (Swift)

查看:151
本文介绍了将UIImage Picker中的图像上传到新的Firebase(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIImagePicker设置在我的应用程序,工作正常。当我的UIImage选择器被选中时,我想上传一个配置文件图片到Firebase。这是我选择照片时的功能。

  //图像选取器完成了代码
func imagePickerController(picker:UIImagePickerController,didFinishPickingMediaWithInfo info:[String:AnyObject] ){

让chosenImage = info [UIImagePickerControllerOriginalImage] as! UIImage
profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage $ b $ profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text =这是你的个人资料图片

dismissViewControllerAnimated(true,completion:nil)



$ / code>

新文档声明我们需要声明一个NSURl来上传一个文件。这里是我试图找到给定文件的NSURL,但它不起作用。以下是文档及其链接: https://firebase.google .com / docs / storage / ios / upload-files#upload_from_data_in_memory

  //位于磁盘$ b上的文件$ b让localFile:NSURL = ... 
//创建一个你想要上传的文件的引用
let riversRef = storageRef.child(images / rivers.jpg)

//将文件上传到路径images / rivers.jpg
let uploadTask = riversRef.putFile(localFile,元数据:nil){元数据,错误
if(error!= nil ){
//呃 - 哦,发生了一个错误!
} else {
//元数据包含文件元数据,如大小,内容类型和下载URL。
让downloadURL =元数据!.downloadURL


code>

这里是我尝试检索UIImagePicker的NSURL:

pre $ $ code图像选择器完成代码
func imagePickerController picker:UIImagePickerController,didFinishPickingMediaWithInfo info:[String:AnyObject]){

let chosenImage = info [UIImagePickerControllerOriginalImage] as! UIImage
//获取对象的URL
让imageUrl = info [UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true).first!作为字符串;
let photoUrl = NSURL(fileURLWithPath:documentDir)
let localPath = photoUrl.URLByAppendingPathComponent(imageName!)
self.localFile = localPath
$ b $ profilePic.contentMode = .ScaleAspectFill
profilePic.image = chosenImage
profilePic.hidden = false
buttonStack.hidden = true
changeButtonView.hidden = false
self.statusLabel.text =Here is Your档案图片

dismissViewControllerAnimated(true,completion:nil)

$ b}

我相信,如果图像是从相机而不是相册拍摄的,我也遇到了困难,因为它还没有保存在设备上。我如何找到这张图片/快照的NSURL?

解决方案

这里是我从firebase存储上传和下载用户个人资料照片的方法:

  func imagePickerController(picker:UIImagePickerController,didFinishPickingImage image:UIImage,editingInfo:[String:AnyObject]?){
userPhoto.image = image
dismissViewControllerAnimated(true,completion:nil)
var data = NSData()
data = UIImageJPEGRepresentation(userPhoto.image!,0.8)!
//设置上传路径
let filePath =\(FIRAuth.auth()!. currentUser!.uid)/ \(userPhoto)
let metaData = FIRStorageMetadata )
metaData.contentType =image / jpg
self.storageRef.child(filePath).putData(data,metadata:metaData){(metaData,error)in $ b $ if if error =错误{
print(error.localizedDescription)
return
} else {
// store downloadURL
let downloadURL = metaData!.downloadURL()!. absoluteString
// store downloadURL at database
self.databaseRef.child(users)。child(FIRAuth.auth()!. currentUser!.uid).updateChildValues([userPhoto:downloadURL])



$ b $ / code $ / pre

我也存储图片网址到firebase数据库,并检查用户是否有个人资料照片或你可能会崩溃:
$ b $ pre $ //获取照片回

databaseRef.child(users) .child(userID!)。observeSingleEventOfType(.Value,withBlock:{(snapshot)in
//检查用户是否有照片
如果snapshot.hasChild(userPhoto){
//设置图像位置
let filePath =\(userID!)/ \(userPhoto)
//假设一个< 10MB文件,尽管你可以改变
self.storageRef.child(filePath).dataWithMaxSize(10 * 1024 * 1024,完成:{(data,error)in

let userPhoto = UIImage (data:data!)
self.userPhoto.image = userPhoto
})
}
})


I have a UIImagePicker set up within my app that works fine. I would like to upload a profile picture to Firebase when my UIImage picker has been chosen. Here is my function for when a picture has been selected.

    //image picker did finish code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
    profilePic.contentMode = .ScaleAspectFill
    profilePic.image = chosenImage
    profilePic.hidden = false
    buttonStack.hidden = true
    changeButtonView.hidden = false
    self.statusLabel.text = "Here is Your Profile Picture"

    dismissViewControllerAnimated(true, completion: nil)


}

The new documentation states that we need to declare a NSURl in order to upload a file. Here is my attempt to find the NSURL of the given file, but it doesn't work. Here is the documentation and a link to it:https://firebase.google.com/docs/storage/ios/upload-files#upload_from_data_in_memory

// File located on disk
let localFile: NSURL = ...
// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putFile(localFile, metadata: nil) { metadata, error in
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    let downloadURL = metadata!.downloadURL
  }
}

Here is my attempt for retrieving the NSURL of the UIImagePicker:

//image picker did finish code
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        //getting the object's url
        let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
        let imageName = imageUrl.lastPathComponent
        let documentDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String;
        let photoUrl = NSURL(fileURLWithPath: documentDir)
        let localPath = photoUrl.URLByAppendingPathComponent(imageName!)
        self.localFile = localPath

        profilePic.contentMode = .ScaleAspectFill
        profilePic.image = chosenImage
        profilePic.hidden = false
        buttonStack.hidden = true
        changeButtonView.hidden = false
        self.statusLabel.text = "Here is Your Profile Picture"

        dismissViewControllerAnimated(true, completion: nil)


    }

I believe that I am also running into difficulties if the image was taken from the camera instead of the gallery since it is not saved on the device yet. How do I find this image/snapshots's NSURL?

解决方案

Here is my method to upload and download the user profile photo from firebase storage:

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    userPhoto.image = image
    dismissViewControllerAnimated(true, completion: nil)
    var data = NSData()
    data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
    // set upload path
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpg"
    self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }else{
        //store downloadURL
        let downloadURL = metaData!.downloadURL()!.absoluteString
        //store downloadURL at database
    self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
        }

        }
                   }

I also storage the Image URL into firebase database and check if user has profile photo or u might get crash :

 //get photo back

     databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            // check if user has photo
            if snapshot.hasChild("userPhoto"){
                // set image locatin
                let filePath = "\(userID!)/\("userPhoto")"
                // Assuming a < 10MB file, though you can change that
                self.storageRef.child(filePath).dataWithMaxSize(10*1024*1024, completion: { (data, error) in

                    let userPhoto = UIImage(data: data!)
                    self.userPhoto.image = userPhoto
                })
            }
        })

这篇关于将UIImage Picker中的图像上传到新的Firebase(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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