Tuesday, November 11, 2014

Uploading to Google Cloud Storage from iOS app

I am using Google appengine for one of my iOS app (IntoMovies: Goodreads for movies and a community for movie and TV show fans - ) and also Google cloud storage to store images uploaded from the app. And, It took me a bit of head scratching to upload photos from iOS directly to google cloud storage. First, I didn't want to use google's iOS library which I think is not very clean and has way more code than it's really needed for simple use case. So i followed few web based samples and got the uploads working.

So, I am directly jumping to some code. I am assuming that you have google app engine project created and Google Cloud Storage is enabled in console's APIs & auth section.

1. Create a bucket in Cloud Storage section of your project's console

2. Create upload servlet or controller in appengine server that does 2 things:

    a) GET request handler that uses appengine's blobstore service to create the upload URL based
        on  bucket name and other   options and return to the client app.

    b)  POST request handler which is basically a callback from google cloud storage once image
         is uploaded to cloud store.

Here's the code for our Upload servlet,

3. Now the fun part, iOS client. Here I have a single method uploadImage that first gets the upload URL and uploads image data to that URL using multipart upload.
Here's the client code

 
One thing to note here is the form data that we pass in such as 'name' and 'filename' these should match the param names that you read in our POST request handler. Also, we are using blobstore to upload images to google cloud storage that way we are not limited by timeout limit on appengine instances. Though, we might need to have a cron job to remove keys from blob store.

Hope this helps!! Feel free to ask questions!

No comments :