Decoding Gmail API downloaded attachment data

1.7k Views Asked by At

I can able to fetch attachment by passing userId, nessageID and attachmentID(For reference:

Google Developer

Cocoa Docs

I'm getting response as like below.

{ "data": "JVBERi0xLjYKJeTjz9IKMSAwIG9iagpbL1BERi9JbWFnZUIvSW1hZ2VDL0l...." "size": 629163 }

I want to decode data to save in my app local and later i will display .

I can successfully downloaded and saved in local(document folder) but not able to see the content in the attachment please make me perfect.

1

There are 1 best solutions below

0
On

I've just succeeded (minutes ago!) to decode the attachment data retrieved, in Swift (sorry I can't code objective-c) so here are steps :

1) Count the number of characters in "data". Base64 encoded strings has to have a number of characters which is a multiple of 4. If this is not the case, you need to pad the end of the string by as many "=" characters as need to reach the next multiple of 4. (I believe Google has sent data without need of patching but you never know...)

2) As I've discovered in this SO link (iOS - download attachment from Gmail using messageId and attachmentId), Google replaced some characters for the HTTP transfers so you need to replace:

  • "-" (minus character) by "+" (plus character)

  • "_" (underscore character) by "/" (slash character)

3) Then convert the "prepared" Base64 string into Data using this Swift Data init method : Data(base64: YourBase64String, options: .ignoreUnknownCharacters)

Then you can save this converted data into a file with the correct extension. I've managed to retrieve jpeg and pdf format attachments.

I hope it works for you.