videos uploaded to firebase are 0 seconds long? - ios

I have an app where you can upload videos to firebase. The problem I have recently encountered is that all videos uploaded to firebase are 0 sec long (This is when in the DB, before, as in in the app, they are of correct length), which is of course wrong.
Some things I've tried:
I check how I upload which i also included bellow and it seems correct.
thumbnail is of type UIImage
The video right before I send it (in the preview I have in-app) the video looks perfect.
Another thing I noticed is that a thumbnail I upload with the video which is an image is being uploaded as a video.
} else if let vidData = media.videoURL {
print("VIDEO")
let autoIDSto = "media\(media.numMedia).mov"
print(autoIDSto)
let autoID = "media\(media.numMedia)"
let storageRef = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post:\(postID)").child(autoIDSto)
let postRef = childRef.child("Media")
let uploadData = media.videoURL
let uploadTask = storageRef.putFile(from: vidData, metadata: nil) { (metadata, error) in
print("\(vidData) : Video data")
guard let metadata = metadata else { return }
if let error = error {
print(error)
}
storageRef.downloadURL(completion: { (url, error) in
//a bunch of code to add to DB
if let thumbnailImageData = media.thumbnailImage!.jpegData(compressionQuality: 1.0) {
storageRef.putData(thumbnailImageData, metadata: nil) { (metadata, error) in
storageRef.downloadURL(completion: { (url, error) in
if let thumbnail = url {
mediaRef.updateChildValues(["thumbnail" : "\(thumbnail)"])
Whats wrong and how can I fix it?

You use the same path ( 1 with mov extension )
let storageRef = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post:\(postID)").child(autoIDSto)
to store the video/image thumbnail here
let uploadTask = storageRef.putFile(from: vidData, metadata: nil) { (metadata, error) in
and
storageRef.putData(thumbnailImageData, metadata: nil) { (metadata, error) in
There should be 2 different paths 1 with mov extension and another with jpg extension that you finally store the reference of both in 1 record in your database table

Related

Error uploading video to cloud storage swiftui

I have a video creating process where a user selects a video using UIImagePickerController. After selecting a video, the url of the video is passed to the video details page. Once the user completes the details and clicks upload, I run this code:
if canProceed(){
let fileName = "\(UUID().uuidString).mov"
storage.reference(withPath: "videos/\(Auth.auth().currentUser?.email ?? "")/\(fileName)").putFile(from: vidURL, metadata: nil) { metadata, err in
if err != nil{
print(err)
return
}
metadata?.storageReference?.downloadURL(completion: { url, err in
if err != nil{
print(err)
return
}
db.collection("reelPool").document(fileName).setData(["url": url])
})
}
}
Nothing is uploaded to cloud storage and the return is:
Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response."
HI I think Here is your answer Just try with it ,
// Url is Video Url Which you will get when Pick a video from Image Picker
func upload(file: URL, completion: #escaping ((_ url : URL?) -> ())) {
let name = "\(yourFile Name)).mp4"
do {
let data = try Data(contentsOf: file)
let storageRef =
Storage.storage().reference().child("Videos").child(name)
if let uploadData = data as Data? {
let metaData = StorageMetadata()
metaData.contentType = "video/mp4"
storageRef.putData(uploadData, metadata: metaData
, completion: { (metadata, error) in
if let error = error {
completion(nil)
}
else{
storageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
completion(nil)
return
}
completion(downloadURL)
}
print("success")
}
})
}
}catch let error {
print(error.localizedDescription)
}
And then You will get Url of the Video, now run code of firestore and Pass Url in dictionary .
Did you remember to edit your Firestore rules to allow for read/write access? Your database may not allow writing or only allow writing for authenticated users. Typically Code -13000 is related to permissioning issues on the database.

How to fix Firebase Storage reference error

I'm getting an error with firebase and my code.
Type 'StorageReference' has no member 'put'
I tried putData and still nothing. what is the best solution to fix this problem?
I'm also getting this error when users tap to pick a profile picture
'UIImageJPEGRepresentation' has been replaced by instance method
'UIImage.jpegData(compressionQuality:)'
StorageReference.put(imageData, metadata: nil, completion: { (metadata, error) in
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1)
theres a article how to upload data to storage on firebase:
https://firebase.google.com/docs/storage/ios/upload-files
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// Metadata contains file metadata such as size, content-type.
let size = metadata.size
// You can also access to download URL after upload.
riversRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
return
}
}
}

ImageView to Firebase Storage in Swift

I am trying to upload an image from ImageView to Firebase storage but it won't work.
I have listed my code below: My image view is called ProfileImage
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = self.ProfileImage.image!.pngData() {
storageRef.putFile(from: uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("error")
completion(nil)
} else {
// your uploaded photo url.
}
}
}
It comes up with the error "Cannot convert value of type 'Data' to expected argument type 'URL'
You are trying to upload Data, not a file. Replace
putFile
With
putData
And it should work fine
Try this code :-
let storageRef = Storage.storage().reference().child("myImage.png")
if let uploadData = UIImagePNGRepresentation(self.profileImage.image!) {
storageRef.put(uploadData, metadata: nil) { (metadata, error) in
if error != nil {
print("\(error.localizeDescription)")
} else {
// your uploaded photo url.
}
}
let refDatabase = Database.database().reference()
var refstorage = Storage.storage().reference()
let data = image.jpegData(compressionQuality: 1.0) //
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let postkey = refDatabase.child("Post").childByAutoId().key
print(postkey)
let imagename = "PostImage/\(postkey).png"
refstorage = refstorage.child(imagename)
let timestamp = Date().timeIntervalSince1970 // you can use this to track time when it was uploaded.
self.refstorage?.putData(data!, metadata: metadata, completion: { (meta, error) in
if error == nil{
if let imageData = meta?.downloadURL()?.absoluteString{
// DO SOMETHING
} else {
print("Couldn't get the URL for image")
}
}
})
I know that this question has been answered, but there is an easier way to do this. Along with import Firebase and Firebase Storage, you will also have to add FirebaseUI to your podfile and import it.
After you have done that, you could get your image to your app much simpler.
let storage = Storage.storage()
let storageRef = storage.reference()
let placeholderImage = UIImage(named: "placeholder.jpeg")
let reference = storageRef.child("myImage.png")
ProfileImage.sd_setImage(with: reference, placeholderImage: placholderImage)
(The placeholder Image would just be a transparent image that you put in your assets folder in XCode that you could reuse multiple times in your application, for whenever you needed to get a Firebase Image on your app.)

Firebase storage how to get uploading images progress in Swift

I'm trying to get progress of uploading images and I saw the explanation link below. However what I want to do is uploading multiple images.
link here
I implemented like this to upload images.
for image in imagesArray {
let postRef = ref.child("post").child(uid)("images")
let autoId = postRef.childByAutoId().key
let childStorageRef = storageRef.child("images").child(autoId)
if let uploadData = UIImagePNGRepresentation(image) {
childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print("error")
return
} else {
if let imageUrl = metadata?.downloadURL()?.absoluteString {
let val = [autoId: imageUrl]
postRef.updateChildValues(val)
}
}
})
}
}
I tried call observe(.progress)
But there is only childStorageRef.observe(<#T##keyPath: KeyPath<StorageReference, Value>##KeyPath<StorageReference, Value>#>, options: <#T##NSKeyValueObservingOptions#>, changeHandler: <#T##(StorageReference, NSKeyValueObservedChange<Value>) -> Void#>)
So, I don't know how to get progress like link.
How can I achieve this? Thank you in advance!
Swift- 5 Easy Way
let storageRef = FIRStorage.reference().child("folderName/file.jpg");
let localFile: NSURL = // get a file;
// Upload the file to the path "folderName/file.jpg"
let uploadTask = storageRef.putFile(localFile, metadata: nil)
uploadTask.observe(.progress) { snapshot in
print(snapshot.progress) // NSProgress object
}
1. First, create a variable of your query:
(Just add "let uploadTask = " before the query)
Example: let uploadTask = childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in...
2. Then you can call this observers:
(Observe progress)
uploadTask.observe(.progress, handler: { (snapshot) in
or
(Observe when success)
uploadTask.observe(.success, handler: { (snapshot) in
or
(Observe if fail)
uploadTask.observe(.failure, handler: { (snapshot) in

Upload AVAsset to Firebase Storage

I'm trying to upload a video that the app has as an AVAsset into Firebase Storage. The problem is that I am having problems both converting it to Data or just uploading as a file. As of now I am trying to export and upload its URL, but the app crasher without explanation (the dreaded (llbd)).
let uuid: String = UUID().uuidString
let imagesRef = storageRef.child("\(uuid)")
let exporter = AVAssetExportSession(asset: videos[i], presetName: AVAssetExportPresetHighestQuality)
let uploadTask = imagesRef.putFile(from: exporter!.outputURL!, metadata: nil) { (metadata, error) in //app crasher here
guard let metadata = metadata else {
return
}
let downloadURL = metadata.downloadURL()
//REST OF CODE
Any ideas how to make this process possible?
I don't know if it's still relevant but you have to use it a new way as:
imagesRef.downloadURL(completion: { (url, error) in //code })
Hope this helps

Resources