Firebase
Storage
Store and serve user-generated content with Cloud Storage.
Overview
Cloud Storage for Firebase lets you upload and share user-generated content like images, videos, and other files.
Uploading Files
Upload a file to Cloud Storage:
import FirebaseStorage
let storage = Storage.storage()
let storageRef = storage.reference()
let imageRef = storageRef.child("images/\(UUID().uuidString).jpg")
let uploadTask = imageRef.putData(imageData, metadata: nil) { metadata, error in
guard metadata != nil else {
return
}
}
Downloading Files
Download a file:
let imageRef = storage.reference().child("images/photo.jpg")
imageRef.getData(maxSize: 10 * 1024 * 1024) { data, error in
if let error = error {
print("Error downloading: \(error)")
} else {
let image = UIImage(data: data!)
}
}
Getting Download URLs
Get a download URL for sharing:
imageRef.downloadURL { url, error in
if let downloadURL = url {
print("Download URL: \(downloadURL)")
}
}
Monitoring Progress
Track upload progress:
uploadTask.observe(.progress) { snapshot in
let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
/ Double(snapshot.progress!.totalUnitCount)
print("Upload is \(percentComplete)% complete")
}
Security Rules
Protect your storage with security rules:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /images/{imageId} {
allow read: if request.auth != null;
allow write: if request.auth != null
&& request.resource.size < 5 * 1024 * 1024
&& request.resource.contentType.matches('image/.*');
}
}
}
Best Practices
- Validate file types and sizes before uploading
- Use unique file names to prevent overwrites
- Delete unused files to save storage costs
- Implement proper security rules