As Firebase Realtime database can only store Json structured data which only accepts key-value pairs, what if I want to share a picture in the room? Here comes the Firebase Cloud Storage.
Setup
- Setup project in Firebase console (covered in previous chapters)
- Create a bucket in panel Firebase->Develop->Storage
- Install SDK: Firebase/Core, Firebase/Storage
- FirebaseApp.configure() in application:didFinishLaunchingWithOptions
Now try create a StorageService and test upload/download. It might be easier to upload an image in Firebase console and test downloading first. My example is as follows:
In order to make the uploaded image to be displayed in chat room, an image name or url need to be updated in realtime database and I added a message type to the existing MessageModel.
In addition, for better user experience, I send a message to realtime database, record the key of the new message and start the upload task at the same time. That will generate a new message on UI since it is driven by database to let user know there is an upload task in progress. Once the upload task finished, I find the new message by the key recorded and update the image name in the message body.
Since this is just a demo, there is big room for improvement:
- Error handling of uploading:
- Only download other user's image when tapped on a thumbnail
- Maximum size of the image can be downloaded. Image resizing.
- Use pause(), resume(), cancel() event to manage the uploading task if anything interrupt it.
- ...
All chapters:
Realtime chat iOS demo (1) - Firebase Realtime Database
Realtime chat iOS demo (2) - Firebase Remote Config
Realtime chat iOS demo (3) - Firebase Cloud Storage
Realtime chat iOS demo (4) - Firebase Cloud Function
Realtime chat iOS demo (5) - Firebase Cloud Messaging
Source code:
TarotChatRoom in Github
No comments:
Post a Comment