web-dev-qa-db-ja.com

UIImage Pickerから新しいFirebase(Swift)への画像のアップロード

アプリ内で正常に動作するUIImagePickerを設定しています。 UIImageピッカーが選択されたときに、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を見つけるにはどうすればよいですか?

9

これが、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])
        }

        }
                   }

また、画像の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
                })
            }
        })
26
Johnny Hsieh

Swift 4.2での作業

ここで私は画像をクリックしてタップジェスチャーを追加し、それからギャラリーを開き、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)
    }


}
0
Yogesh Patel