skip to Main Content

I am trying to upload profile pictures to my firebase storage using swift.
The problem is that when the user posts a new profile picture, it doesn’t overwrite the first one. On my app, it still shows the old one, even though on the database, it shows the new one is uploaded.

This is how I am loading the image

let storage = Storage.storage()
let storageRef = storage.reference()

let ref = storageRef.child("(UserModel.docId)-ProfilePicture")

// check if file exists or not
ref.downloadURL { newUrl, error in
    if let error = error {
        print("Image does not exist")
        self.profileImage.image = UIImage(systemName: "person.circle.fill")
    } else {
        print("loaded database image")
        self.profileImage.sd_setImage(with: ref)
    }
}

This is how I am uploading the image.

let storage = Storage.storage()
let storageRef = storage.reference()
let photoRef = storageRef.child("(UserModel.docId)-ProfilePicture")
let data = Data()


let uploadTask = photoRef.putFile(from: fileURL,metadata: nil) {(metadata,err)  in
    guard let metadata = metadata else {
        print("error uploading to database")
        return
    }
    print("Photo uploaded")
}

There are no errors.

2

Answers


  1. Chosen as BEST ANSWER

    The solution was to clear the cache before downloading the files, like this :

    SDImageCache.shared.clearDisk()
    

  2. What I would do is convert the UIImage to Data using the following UIImage method:

    public func jpegData(compressionQuality: CGFloat) -> Data?
    

    You can call that function directly on your image to get back Data which you can then use to upload to Storage.

    // handy extension
    extension StorageMetadata {
        enum MetadataContentType: String {
            case jpeg = "image/jpeg"
        }
        
        convenience init(contentType: MetadataContentType) {
            self.init()
            self.contentType = contentType.rawValue
        }
    }
    
    let storage = Storage.storage()
    let remotePath = "(UserModel.docId)-ProfilePicture"
    let metadata = StorageMetadata(contentType: .jpeg)
    
    storage.reference(withPath: remotePath).putData(theJPEGData, metadata: metadata) { (metadata, error) in
        if let _ = metadata {
            // success
        } else {
            if let error = error {
                print(error)
            }
            // failure
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search