So I am using Firebase for the first time. I have read that you should store videos in Storage and then store that unique URL in their Database. How would I take this approach? For example if a user request a specific video to play how would I grab the URL from the database and then with that url pull the video out of the database?
Thank for the help and excuse my inexperience with Firebase.
2020: Yes, firebase storage video streaming is easy and possible.
Once you have a reference, you can download files from Cloud Storage by calling the getBytes() or getStream() . If you prefer to download the file with another library, you can get a download URL with getDownloadUrl() .
Image URL is obtained by uploading an image to firebase bucket and then that can return back a URL that URL is a permanent URL which can be open anywhere. Then a user can use this URL for any purpose in its application.
From the Zero to App talk at Google I/O comes this code:
// pragma mark - UIImagePickerDelegate overrides
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// Get local file URLs
guard let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
let imageData = UIImagePNGRepresentation(image)!
guard let imageURL: NSURL = info[UIImagePickerControllerReferenceURL] as? NSURL else { return }
// Get a reference to the location where we'll store our photos
let photosRef = storage.reference().child("chat_photos")
// Get a reference to store the file at chat_photos/<FILENAME>
let photoRef = photosRef.child("\(NSUUID().UUIDString).png")
// Upload file to Firebase Storage
let metadata = FIRStorageMetadata()
metadata.contentType = "image/png"
photoRef.putData(imageData, metadata: metadata).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let text = snapshot.metadata?.downloadURL()?.absoluteString
// Set the download URL to the message box, so that the user can send it to the database
self.messageTextField.text = text
}
// Clean up picker
dismissViewControllerAnimated(true, completion: nil)
}
This takes the image that was selected in the image picker, uploads it to Firebase Storage and then sets the resulting download URL for that image into a text field:
// Send a chat message
func sendMessage(sender: AnyObject) {
// Create chat message
let chatMessage = ChatMessage(name: self.username, message: messageTextField.text!, image: nil)
messageTextField.text = ""
// Create a reference to our chat message
let chatRef = database.reference().child("chat")
// Push the chat message to the database
chatRef.childByAutoId().setValue(["name": chatMessage.name, "message": chatMessage.message])
}
The sendMessage
method then sends the text from the text box to the database.
Full code for that minimal example is in this gist.
Here is my solution to store Videos into Firebase Storage. For Swift 3.
func uploadVideo(_ path: URL, _ userID: String,
metadataEsc: @escaping (URL, FIRStorageReference)->(),
progressEsc: @escaping (Progress)->(),
completionEsc: @escaping ()->(),
errorEsc: @escaping (Error)->()) {
let localFile: URL = path
let videoName = getName()
let nameRef = StorageHandler.videosRef.child(userID).child(videoName)
let metadata = FIRStorageMetadata()
metadata.contentType = "video"
let uploadTask = nameRef.putFile(localFile, metadata: metadata) { metadata, error in
if error != nil {
errorEsc(error!)
} else {
if let meta = metadata {
if let url = meta.downloadURL() {
metadataEsc(url, nameRef)
}
}
}
}
_ = uploadTask.observe(.progress, handler: { snapshot in
if let progressSnap = snapshot.progress {
progressEsc(progressSnap)
}
})
_ = uploadTask.observe(.success, handler: { snapshot in
if snapshot.status == .success {
uploadTask.removeAllObservers()
completionEsc()
}
})
}
func getName() -> String {
let dateFormatter = DateFormatter()
let dateFormat = "yyyyMMddHHmmss"
dateFormatter.dateFormat = dateFormat
let date = dateFormatter.string(from: Date())
let name = date.appending(".mp4")
return name
}
Called by:
StorageHandler.shared.uploadVideo(myFileURL, myUserID, metadataEsc: { (url, ref) in
print("url = \(url)") // here is the URL you can then store into your Firebase tree
print("ref = \(ref)")
}, progressEsc: { progress in
print("progress = \(progress)")
}, completionEsc: {
print("done")
}, errorEsc: { error in
print("*** Error during file upload: \(error.localizedDescription)")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With