2016-08-20 7 views
-2

Ich möchte in meiner iOS-Anwendung eine Schaltfläche erstellen. Wenn der Benutzer darauf klickt, erhält er zwei Optionen: entweder ein Foto aus dem Album auswählen oder Machen Sie ein Foto von der Kamera zur Firebase-Datenbank.Hochladen eines Bildes aus der Fotobibliothek oder Kamera in den Firebase-Speicher (Swift)

Was ist die Struktur, die ich folgen muss, um dies zu ermöglichen? Hochladen des Bildes in die Firebase-Datenbank!

+0

Wie ist Firebase in Ihrer Frage beteiligt? – EBDOKUM

+0

@ EBDOKUM Weil ich das gewählte oder aufgenommene Bild in Firebase speichern möchte! – Mariah

+0

@ EBDOKUM Hast du verstanden was ich meine? – Mariah

Antwort

4

Stellen Sie sicher, dass Ihren ersten View-Controller in Storyboard haben einen Navigations Controller angeschlossen

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 Funktionen: -

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: - Der Repo-Link könnte in Zukunft nützlich sein :) https://github.com/firebase/quickstart-ios (Firebase offizielle Probe)

+0

Ich habe den ersten Teil ausprobiert und es hat funktioniert! Aber ich werde nicht versuchen, den zweiten Teil, bis ich viel über uiimagepickercontroller lesen und https://github.com/firebase/quickstart-ios Beispiele nicht nur kopieren und pase den Code sehen! Vielen Dank! – Mariah

+0

Vermeiden Sie Fragen im Kommentar zu stemmen. Schreibe einen neuen ... – Dravidian

Verwandte Themen