swift2 将图像从UIImage Picker上传到新的Firebase(Swift)

oug3syen  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(190)

我在我的应用程序中设置了一个UIImagePicker,它工作正常。当我的UIImagePicker被选中时,我想上传一张个人资料图片到Firebase。下面是我在选择图片时的函数。

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

}

新的文档说明我们需要声明一个NSURL才能上传文件。下面是我试图找到给定文件的NSURL的尝试,但是没有成功。下面是文档和它的链接: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
  }
}

以下是我尝试检索UIImagePicker的NSURL的过程:

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

    }

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

uyto3xhc

uyto3xhc1#

下面是我从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)!
    // 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])
        }

        }
                   }

我还将图像URL存储到firebase数据库中,并检查用户是否有个人资料照片,否则可能会导致崩溃:

//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
                })
            }
        })
3zwjbxry

3zwjbxry2#

简单的2020年例子

1.别忘了将pod 'Firebase/Storage'添加到您的podfile中,并且pod install
1.将两个代表添加到您的类中

class YourScreen: UIViewController, 
  UIImagePickerControllerDelegate, UINavigationControllerDelegate {

1.情节提要、按钮、链接到...

@IBAction func tapCameraButton() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}

然后再

func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

 guard let im: UIImage = info[.editedImage] as? UIImage else { return }
 guard let d: Data = im.jpegData(compressionQuality: 0.5) else { return }

 let md = StorageMetadata()
 md.contentType = "image/png"

 let ref = Storage.storage().reference().child("someFolder/12345678.jpg")

 ref.putData(d, metadata: md) { (metadata, error) in
     if error == nil {
         ref.downloadURL(completion: { (url, error) in
             print("Done, url is \(String(describing: url))")
         })
     }else{
         print("error \(String(describing: error))")
     }
 }

 dismiss(animated: true)
}

但你把图像放在哪里?

在代码处,

... .child("someFolder/12345678.jpg")

几乎不可避免地,
·使用用户ID、聊天ID、订阅源ID或类似概念作为文件夹名称
·对于名称,唯一可能的是uuid
因此几乎总是

let f = chatId + "/" + UUID().uuidString + ".jpg"
let ref = Storage.storage().reference().child(f)
pgpifvop

pgpifvop3#

在Swift 4.2中工作
在这里,我做点击图像,我已经添加了tapGesture,然后它打开画廊,然后选择图像,上传在Firebase,也我添加textField值太我希望它能帮助你,谢谢

import UIKit
import Firebase
class ViewController: UIViewController {

    @IBOutlet var myImageView: UIImageView!
    @IBOutlet var txtText: UITextField!
    var ref = DatabaseReference.init()
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.ref = Database.database().reference()
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.openGalleryClick(tapGesture:)))
        myImageView.isUserInteractionEnabled = true
        myImageView.addGestureRecognizer(tapGestureRecognizer)
        myImageView.backgroundColor = UIColor.red
    }

    @objc func openGalleryClick(tapGesture: UITapGestureRecognizer){
        self.setupImagePicker()
    }

    @IBAction func btnSaveClick(_ sender: UIButton) {
         self.saveFIRData()
    }

    func saveFIRData(){
        self.uploadMedia(image: myImageView.image!){ url in
            self.saveImage(userName: self.txtText.text!, profileImageURL: url!){ success in
                if (success != nil){
                    self.dismiss(animated: true, completion: nil)
                }

            }
        }
    }

    func uploadMedia(image :UIImage, completion: @escaping ((_ url: URL?) -> ())) {
        let storageRef = Storage.storage().reference().child("myimage.png")
        let imgData = self.myImageView.image?.pngData()
        let metaData = StorageMetadata()
        metaData.contentType = "image/png"
        storageRef.putData(imgData!, metadata: metaData) { (metadata, error) in
            if error == nil{
                storageRef.downloadURL(completion: { (url, error) in
                    completion(url)
                })
            }else{
                print("error in save image")
                completion(nil)
            }
        }
    }

    func saveImage(userName:String, profileImageURL: URL , completion: @escaping ((_ url: URL?) -> ())){
        let dict = ["name": "Yogesh", "text": txtText.text!, "profileImageURL": profileImageURL.absoluteString] as [String : Any]
        self.ref.child("chat").childByAutoId().setValue(dict)
    }

}

extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate{

    func setupImagePicker(){
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            imagePicker.sourceType = .savedPhotosAlbum
            imagePicker.delegate = self
            imagePicker.allowsEditing = true

            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        myImageView.image = image
        picker.dismiss(animated: true, completion: nil)
    }

}

相关问题