Swift Firebase Storage.storage().reference(forURL: ) not working - ios

Suddenly my reference to to my Storage to retrieve images to share is not working anymore. It was literally just working 30 minutes ago but being very inconsistent. Do I have to add new security rules or something? But I guess welcome to programming where code magically stops working lol.
let ref = Storage.storage().reference(forURL: pictureImage)
ref.getData(maxSize: 2 * 1024 * 1024, completion: {(data, error) in
if error != nil {
print("image could not be downloaded")
} else {
if let imgData = data {
if let img = UIImage(data: imgData) {
objectsToShare.append(img)
print("image downloaded")
}
}
}
})
Update
When I use this call it works, yet my "getData" call has stopped working...
let storageRef = Storage.storage().reference(forURL: pictureImage)
storageRef.delete(completion: { error in
if let error = error {
print(error)
} else {
print("Successful Delete")
}
})

Same is working for me
func downloadImageUserFromFirebase(Link:String) {
let storageRef = Storage.storage().reference(forURL: Link)
storageRef.getData(maxSize: 2 * 1024 * 1024) { (data, error) in
if error == nil {
if let imgData = data {
if let img = UIImage(data: imgData) {
print("got imagedata \(String(describing: imgData))")
// objectsToShare.append(img)
print("image downloaded")
}
}
} else {
print("ERROR DOWNLOADING IMAGE : \(String(describing: error))")
}
}
}
Seems like you Had made some changes in your Rules

Well for me the problem was that I was missing the -ObjC flag in Other linker flags in my app's build settings.

Related

I want to pick video from Imagepicker then I want to send video in firebase and retrieve it

I want to pick video from Images Picker then I want to send video in firebase and retrieve it Please provide code in swift 5, i write code also for sending video on firebase
func downloadImages(folderPath:String,success:#escaping (_ image:UIImage)->(),failure:#escaping (_ error:Error)->()){
// Create a reference with an initial file path and name
let reference = Storage.storage().reference(withPath: "\(folderPath)")
reference.getData(maxSize: (1 * 1024 * 1024 * 1024 * 1024 * 1024)) { (data, error) in
if let _error = error{
print(_error)
failure(_error)
} else {
if let _data = data {
let myImage:UIImage! = UIImage(data: _data)
success(myImage)
}
}
}
}
Upload video On firebase Storage is
func upload(file: URL, completion: #escaping ((_ url : URL?) -> ())) {
let name = "\(Int(Date().timeIntervalSince1970)).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 Get Video From firebase
let reference = Storage.storage().reference().child("Videos").child(folderPath)
reference.getData(maxSize: INT64_MAX) { (data, error) in
if let error = error {
print("Error downloading image data: \(error)")
return
}
reference.getMetadata(completion: { (metadata, metadataErr) in
if let error = metadataErr {
print("Error downloading metadata: \(error)")
return
}
else {
reference.downloadURL { URL, error in
completion(URL)
print(URL)
}

Not able to get the url of uploaded image on firebase storage

class FCMStorage {
var storage: Storage!
init() {
storage = Storage.storage()
}
func storeImage(data: Data?, name: String, completion: #escaping ((String?, Error?)->Void)) {
guard let data = data else {
return
}
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
let path = "images/" + name
print("img to store = \(path)")
let ref = storage.reference()
let uploadTask = ref.child(path).putData(data, metadata: metaData) { (metadata, error) in
if error == nil {
print(metadata as Any)
ref.downloadURL(completion: { (url, error) in
completion(url?.absoluteString, error)
})
} else {
print("storeImage error: \(error!)")
}
}
uploadTask.observe(.progress) { (snapshot) in
print((snapshot.progress?.fractionCompleted ?? 0) * 100.0)
if snapshot.status == .success || snapshot.status == .failure {
uploadTask.removeAllObservers(for: .progress)
}
}
}
}
Using the able class I am able to upload the image on firebase successfully and I am able to see the uploaded image on the firebase too but...
When I call downloadURL() method it always giving me the following error
ref.downloadURL(completion: { (url, error) in
completion(url?.absoluteString, error)
})
Error: Failed to retrieve a download URL.
Anyone could help me out on this issue!!
EDIT
When I print metadata of the file it prints the following....
FIRStorageMetadata 0x283f99860: {
bucket = "sportoilic.appspot.com";
contentDisposition = "inline; filename*=utf-8''8E13A816-FAF1-47ED-8F84-94BBB8C4C77F";
contentEncoding = identity;
contentType = "application/octet-stream";
generation = 1601287237056536;
md5Hash = "VgMH6NMPGJT//LCD8goaDA==";
metageneration = 1;
name = "8E13A816-FAF1-47ED-8F84-94BBB8C4C77F";
size = 114787;
timeCreated = "2020-09-28T10:00:37.056Z";
updated = "2020-09-28T10:00:37.056Z";
}
and after that when I try to get the download url for the uploaded image< I am getting the above mentioned error(Error: Failed to retrieve a download URL).
What is the issue? Am I missing something here?
After trial and error of several hours, finally got the solution.
class FCMStorage {
var ref: StorageReference!
init(path: String) {
ref = Storage.storage().reference(withPath: path)
print("img to store at path = \(path)")
}
func storeImage(data: Data?, completion: #escaping ((String?, Error?)->Void)) {
guard let data = data else {
return
}
let uploadTask = ref.putData(data, metadata: nil) { (metadata, error) in
if error == nil {
print(metadata as Any)
self.ref.downloadURL(completion: { (url, error) in
completion(url?.absoluteString, error)
})
} else {
print("storeImage error: \(error!)")
}
}
uploadTask.observe(.progress) { (snapshot) in
print((snapshot.progress?.fractionCompleted ?? 0) * 100.0)
if snapshot.status == .success || snapshot.status == .failure {
uploadTask.removeAllObservers(for: .progress)
}
}
}
}
So store image just need to call like this...
let path = "images/" + UUID().uuidString
FCMStorage(path: path).storeImage(data: data) { (imgUrl, error) in
if let strUrl = imgUrl, error == nil {
FCMDatabase.init(OfTable: .chatRooms).setImageUrl(strUrl: strUrl, teamId: self.team?.id ?? 0, forMsgId: self.arrChats.last?.messageId ?? "") { (isDone) in
if isDone {
print("Image url set in database")
}
}
} else {
print("Error: \(error?.localizedDescription ?? "Error while getting image url")")
}
}

Firebase: Returning a UIImage from URL returns void

Just wondering if anyone knows why my below code returns void instead of a UIImage.
func getImageFromURL(imageURL : String) -> UIImage {
let ref = Storage.storage().reference(forURL: imageURL)
ref.getData(maxSize: 2 * 1024 * 1024) { (data, error) in
if error != nil {
print("ERROR: Image not downloaded from Firebase.")
} else {
print("SUCCESS: Image downloaded from Firebase Storage")
let img = UIImage(data: data!)
return img
}
}
}

Value of type 'StorageReference' has no member 'data'

This code would have worked a few months ago, I have checked some other code on GitHub and verified that this code would have worked in the past but I am having trouble finding a solution. I've looked for a solution using Firebase Migration Support, but I've had no luck. Thank you in advance!
func configCell(searchDetail: Search) {
self.searchDetail = searchDetail
nameLbl.text = searchDetail.username
let ref = Storage.storage().reference(forURL: searchDetail.userImg)
//Error Below, highlighting 'ref.data' Error: Value of type 'StorageReference' has no member 'data'.
ref.data(withMaxSize: 1000000, completion: { (data, error) in
if error != nil {
print(" we couldnt upload the img")
} else {
if let imgData = data {
if let img = UIImage(data: imgData) {
self.userImage.image = img
}
}
}
})
}
From the migration guide that you have added, you need to now use new getData(maxSize:completion:) instead of data(withMaxSize:completion:). So make it like this.
ref.getData(maxSize: 1000000, completion: { (data, error) in
if error != nil {
print(" we couldnt upload the img")
} else {
if let imgData = data,let img = UIImage(data: imgData) {
self.userImage.image = img
}
}
})

UITableViewCell Image not loading

I want to download images from firebase storage and load it in the tableview but it is not working.
My downloadUrl is right and there is no error.
URLSession.shared.dataTask(with: downloadURL) { (data, response, error) in
if error != nil {
print(error?.localizedDescription)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!) {
cell.imageView?.image = downloadedImage
}
}
}
Why not just use Firebase Storage's built in download mechanisms for this?
let httpsReference = FIRStorage.storage().referenceForURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg') // your download URL
httpsReference.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Data for "images/stars.jpg" is returned
let starsImage: UIImage! = UIImage(data: data!)
cell.imageView.image = starsImage // by default, callbacks are raised on the main thread so this will work
}
}

Resources