Swift+Firebase开发社交APP遇报错:StorageMetadata无downloadURL成员
Fix for "Value of type 'StorageMetadata' has no member 'downloadURL'" Error
Hey there! That error pops up because Firebase Storage updated its SDK and moved the downloadURL() method from StorageMetadata to the actual StorageReference object. Your original code is using the old deprecated approach. Here's the fixed version of your setupUser function, with added safety checks to avoid crashes too:
func setupUser(userUid: String) { // Safely unwrap optional values to avoid crashes guard let imageData = self.userImgView.image?.jpegData(compressionQuality: 0.2), let username = self.usernameField.text, !username.isEmpty else { print("Please select an image and enter a username") return } let imgUid = NSUUID().uuidString let storageRef = Storage.storage().reference().child(imgUid) let metaData = StorageMetadata() storageRef.putData(imageData, metadata: metaData) { (metadata, error) in // Handle upload errors first if let error = error { print("Image upload failed: \(error.localizedDescription)") return } // Get download URL from the storage reference (new SDK approach) storageRef.downloadURL { (url, error) in if let error = error { print("Failed to retrieve download URL: \(error.localizedDescription)") return } guard let downloadURL = url?.absoluteString else { print("Could not convert URL to string") return } let userData = [ "username": username, "userImg": downloadURL ] as [String : Any] // Save user data to database with error handling Database.database().reference().child("users").child(userUid).setValue(userData) { (error, ref) in if let error = error { print("Failed to save user data: \(error.localizedDescription)") return } self.performSegue(withIdentifier: "toFeed", sender: nil) } } } }
Key Changes Explained:
- Switched to StorageReference for downloadURL: The
downloadURL()method no longer exists onStorageMetadatain newer Firebase SDKs—we now call it directly on the storage reference we created (storageRef). - Removed force unwraps: Replaced risky
!with optional bindings (guard let,if let) to prevent crashes if the image, username, or URL is missing. - Added error handling: Added checks for upload failures, URL retrieval issues, and database save errors to help you debug unexpected issues.
- Reused storage reference: Stored the reference in a variable so we don't have to recreate it when fetching the download URL.
内容的提问来源于stack exchange,提问作者Wonixer A
相关产品推荐
相关产品推荐

