Как я могу отправить 5 изображений в хранилище firebase и сохранить URL-адрес пользователю в базе данных в реальном времени в ios - PullRequest
0 голосов
/ 07 мая 2020

это код загружаемого изображения, в котором есть библиотека BSImagePicker, которая позволяет мне выбирать несколько изображений

import UIKit
import Photos
import Firebase
import BSImagePicker

class Downloadimages: UIViewController {

    var firfile: FirFile?
    @IBOutlet weak var imgView: UIImageView!
    let storage = Storage.storage()
    var SelectedAssets = [PHAsset]()
    var PhotoArray = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let storageRef = storage.reference()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func addImagesClicked(_ sender: Any) {
        // create an instance
        let vc = BSImagePickerViewController()

        //display picture gallery
        self.bs_presentImagePickerController(vc, animated: true,
                                             select: { (asset: PHAsset) -> Void in

        }, deselect: { (asset: PHAsset) -> Void in
            // User deselected an assets.

        }, cancel: { (assets: [PHAsset]) -> Void in
            // User cancelled. And this where the assets currently selected.
        }, finish: { (assets: [PHAsset]) -> Void in
            // User finished with these assets
            for i in 0..<assets.count
            {
                self.SelectedAssets.append(assets[i])

            }

            self.convertAssetToImages()

        }, completion: nil)

        /// This is your images array

        let images = [image1, image2, image3, image4, image5]()

        /// Here is the completion blockUse of unresolved identifier 'image1'
        typealias FileCompletionBlock = () -> Void
        var block: FileCompletionBlock?


        func startUploading(completion: @escaping FileCompletionBlock){
             if images.count == 0 {
                completion()
                return;
             }

             block = completion
             uploadImage(forIndex: 0)
        }

        func uploadImage(forIndex index:Int) {

             if index < images.count {
                  /// Perform uploading
                  let data = UIImagePNGRepresentation(images[index])!
                  let fileName = String(format: "%@.png", "multi images")

                  FirFile.shared.upload(data: data, withName: fileName, block: { (url) in
                      /// After successfully uploading call this method again by increment the **index = index + 1**
                      print(url ?? "Couldn't not upload. You can either check the error or just skip this.")
                    uploadImage(forIndex: index + 1)
                   })
                return;
              }

              if block != nil {
                 block!()
              }
        }
    }

    func convertAssetToImages() -> Void {
        if SelectedAssets.count != 0{
            for i in 0..<SelectedAssets.count{

                let manager = PHImageManager.default()
                let option = PHImageRequestOptions()
                var thumbnail = UIImage()
                option.isSynchronous = true

                manager.requestImage(for: SelectedAssets[i], targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: option, resultHandler: {(result, info)->Void in
                    thumbnail = result!

                })

                let data = UIImageJPEGRepresentation(thumbnail, 0.7)
                let newImage = UIImage(data: data!)
                self.PhotoArray.append(newImage! as UIImage)
            }

            self.imgView.animationImages = self.PhotoArray
            self.imgView.animationDuration = 3.0
            self.imgView.startAnimating() 
        }
        print("complete photo array \(self.PhotoArray)")
    }
}

это еще один код, который я взял из другого сообщения и попытался заставить его работать, но у меня не получилось

import UIKit
import Firebase

class FirFile: Downloadimages {

     var  downloadimages: Downloadimages?
    /// Singleton instance
    static let shared: FirFile = FirFile()

    /// Path
    let kFirFileStorageRef = Storage.storage().reference().child("multi images")

    /// Current uploading task
    var currentUploadTask: StorageUploadTask?

    func upload(data: Data,
                withName fileName: String,
                block: @escaping (_ url: String?) -> Void) {

        // Create a reference to the file you want to upload
        let fileRef = kFirFileStorageRef.child("multi images")

        /// Start uploading
        upload(data: data, withName: fileName, atPath: fileRef) { (url) in
            block(url)
        }
    }

    func upload(data: Data,
                withName fileName: String,
                atPath path:StorageReference,
                block: @escaping (_ url: String?) -> Void) {

        // Upload the file to the path
        self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
            guard metaData != nil else{
                //guard let metadata = metaData else
                  // Uh-oh, an error occurred!
                  block(nil)
                  return
             }
             // Metadata contains file metadata such as size, content-type.
             // let size = metadata.size
             // You can also access to download URL after upload.
             path.downloadURL { (url, error) in
                guard url != nil else {
                    //guard let downloadURL = url else
                     // Uh-oh, an error occurred!
                     block(nil)
                     return
                  }
                block ("url")
             }
        }
    }

    func cancel() {
        self.currentUploadTask?.cancel()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...