【问题标题】:Uploading an image from Photo Library or Camera to Firebase storage (Swift) [closed]将图片从照片库或相机上传到 Firebase 存储(Swift)[关闭]
【发布时间】:2016-12-27 14:19:51
【问题描述】:

我想在我的 iOS 应用程序中创建一个按钮,当用户单击它时,他/她有两个选择:从相册中选择一张照片,或者从相机中将照片拍摄到 firebase 数据库。

我必须遵循什么结构才能使这成为可能?将图像上传到 firebase 数据库!

【问题讨论】:

  • 您的问题如何涉及firebase?
  • @EBDOKUM 因为我想将选择或拍摄的图像保存到 firebase!
  • @EBDOKUM 你明白我的意思了吗?
  • 我明白了,但是您的问题并没有询问有关 firebase 的任何内容,为什么要将其包含在您的标题和标签中?¿
  • 无论如何,只要谷歌“uiimagepickercontroller”

标签: ios swift image camera firebase-storage


【解决方案1】:

确保故事板中的第一个视图控制器连接到导航控制器

 class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{

  var imagePicker : UIImagePickerController = UIImagePickerController()

  override func viewDidLoad() {
    super.viewDidLoad()

    imagePicker.delegate = self
   }



     //============================================================================================================================================================

//////
//
//PROFILE PICTURE FUNCTIONS
//
/////




@IBAction func addPictureBtnAction(sender: UIButton) {

    addPictureBtn.enabled = false

    let alertController : UIAlertController = UIAlertController(title: "Title", message: "Select Camera or Photo Library", preferredStyle: .ActionSheet)
    let cameraAction : UIAlertAction = UIAlertAction(title: "Camera", style: .Default, handler: {(cameraAction) in
        print("camera Selected...")

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {

            self.imagePicker.sourceType = .Camera
            self.present()

        }else{
            self.presentViewController(self.showAlert("Title", Message: "Camera is not available on this Device or accesibility has been revoked!"), animated: true, completion: nil)

        }

    })

    let libraryAction : UIAlertAction = UIAlertAction(title: "Photo Library", style: .Default, handler: {(libraryAction) in

        print("Photo library selected....")

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) == true {

            self.imagePicker.sourceType = .PhotoLibrary
            self.present()

        }else{

           self.presentViewController(self.showAlert("Title", Message: "Photo Library is not available on this Device or accesibility has been revoked!"), animated: true, completion: nil)
        }
    })

    let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel , handler: {(cancelActn) in
    print("Cancel action was pressed")
    })

    alertController.addAction(cameraAction)

    alertController.addAction(libraryAction)

    alertController.addAction(cancelAction)

    alertController.popoverPresentationController?.sourceView = view
    alertController.popoverPresentationController?.sourceRect = view.frame

    self.presentViewController(alertController, animated: true, completion: nil)



}

func present(){

        self.presentViewController(imagePicker, animated: true, completion: nil)

}


func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
     print("info of the pic reached :\(info) ")
     self.imagePicker.dismissViewControllerAnimated(true, completion: nil)

}




//Show Alert


func showAlert(Title : String!, Message : String!)  -> UIAlertController {

    let alertController : UIAlertController = UIAlertController(title: Title, message: Message, preferredStyle: .Alert)
    let okAction : UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { (alert) in
        print("User pressed ok function")

    }

    alertController.addAction(okAction)
    alertController.popoverPresentationController?.sourceView = view
    alertController.popoverPresentationController?.sourceRect = view.frame

    return alertController
  }

}

Firebase 功能:-

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!)"

            print("filePath : \(filePath)")


                FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: {



                    (metadata, error) in

                         if error != nil{

                            print("error in uploading image : \(error)")

                            self.delegate.firShowAlert("Error Uploading Your Profile Pic", Message: "Please check your network!")

                         }
                          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!")

    }
}






//Saving the path in your core data to search through later when you retrieve your picture from DB


func uploadSuccess(metadata : FIRStorageMetadata , storagePath : String)
{


    print("upload succeded!")

    print(storagePath)

    NSUserDefaults.standardUserDefaults().setObject(storagePath, forKey: "storagePath.\((FIRAuth.auth()?.currentUser?.uid)!)")

    NSUserDefaults.standardUserDefaults().synchronize()

}

ps: - 这个 repo 链接将来可能有用:) https://github.com/firebase/quickstart-ios(firebase 官方示例)

【讨论】:

  • 我尝试了第一部分,它成功了!但是我不会尝试第二部分,直到我阅读了很多关于 uiimagepickercontroller 的内容并查看github.com/firebase/quickstart-ios 示例,而不仅仅是复制和粘贴代码!谢谢!
  • 避免在评论中使用词干问题。发布一个新的...
猜你喜欢
  • 2019-04-18
  • 2018-02-14
  • 2017-03-26
  • 2017-06-16
  • 1970-01-01
  • 2020-12-25
  • 2020-04-01
相关资源
最近更新 更多