iOS-使用messageId和attachmentId从Gmail下载附件 [英] iOS - download attachment from Gmail using messageId and attachmentId

查看:91
本文介绍了iOS-使用messageId和attachmentId从Gmail下载附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的iOS项目中关注Google Gmail API 文档,需要通过使用userId,messageId和id从邮件中下载附件尝试一下.仅输入您的EmailId ) messageId是我们通过使用具有附件的上述id之一获得的.

I am following Google Gmail API documentation in my iOS project where I need to download an attachment from a mail by using it userId, messageId and id Try out from Google. Where userId is user's Email address, id is mailId (Try it.Enter only your EmailId) messageId is which we get by using an one of above id which has an attachment.

到目前为止,这是我所拥有的代码:

This is so far the code which I am have:

- (void)fetchLabels {
    GTLQueryGmail *query = [GTLQueryGmail queryForUsersThreadsList];
    [self.service executeQuery:query
                      delegate:self
            didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}

- (void)displayResultWithTicket:(GTLServiceTicket *)ticket
             finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
                          error:(NSError *)error {

    NSDictionary *allIDsDictionaryValue=[labelsResponse.JSON valueForKey:@"threads"];
    NSMutableArray *allIDs=[NSMutableArray new];
    for (int i=0; i<[allIDsDictionaryValue count]; i++) {
        [allIDs addObject:[allIDsDictionaryValue valueForKey:@"id"]];
    }
   NSString *mailID=[[allIDs objectAtIndex:0]objectAtIndex:0];
    NSLog(@"%@",mailID);//Ex: 14e8af86776e595b 
    //As of now I am using the first id only because it has an attachment.

   // Getting messageId from an id of a mail.
    GTLQueryGmail *query1 = [GTLQueryGmail queryForUsersMessagesGet];
    query1.identifier=mailID;
    [self.service executeQuery:query1
                      delegate:self
             didFinishSelector:@selector(displayResultWithTicketOfAttachment:finishedWithObject:error:)];
}

- (void)displayResultWithTicketOfAttachment:(GTLServiceTicket *)ticket
             finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
                          error:(NSError *)error {

    NSDictionary *response1=labelsResponse.JSON;
    NSDictionary *response2=[[[response1 valueForKey:@"payload"] valueForKey:@"parts"]objectAtIndex:1];
    if ([[response2 valueForKey:@"mimeType"] isEqualToString:@"application/vnd.ms-excel"]) {
         attachmentId=[[response2 valueForKey:@"body"]valueForKey:@"attachmentId"];
         NSLog(@"%@",attachmentId); //Ex: ANGjdJ_Uw2o7G2Q16jfC4JSTwD2UIO6LuqDIJZvXFCft0q5ALYuiYfM2gPWG0dcty2n6ZkjnVWekIb_3e2_0TqSpctWNAABsfaSF2x2ktf9uHu63e3eIot_GFA9xgppmaRDyaJEL1V-gIvjfPRxgINK8xM0OuuwnVz2xzcCFckkwpK2XwzZG_QPGPvC2Be2bGKNJI8Ds3hGtqfHYeSWZjOjbsjBuxbUFjf1Mlp0TLol9LLAy2cjGZ_CUBQXzZhhWw9AtNHTU4jwhk4WizKRXbfuDvmRtAy1lPCnTKS6pLg

///Based on id and messageId, I am trying to download the attachment
        GTLQueryGmail *query2 = [GTLQueryGmail queryForUsersMessagesAttachmentsGet];
        query2.identifier=mailID;
        query2.messageId=attachmentId;
        [self.service executeQuery:query2
                          delegate:self
                 didFinishSelector:@selector(displayResultWithTicketOfDownloadAttachment:finishedWithObject:error:)];
    }else{
        UIAlertView *alertShow=[[UIAlertView alloc]initWithTitle:@"Error" message:@"No Attachment found" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alertShow show];
    }
}

- (void)displayResultWithTicketOfDownloadAttachment:(GTLServiceTicket *)ticket
                         finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
                                      error:(NSError *)error {
    NSLog(@"response is :%@",labelsResponse.JSON);
     NSLog(@"error is :%@",error);
}

But I am getting error as : Error Domain=com.google.GTLJSONRPCErrorDomain Code=400 "The operation couldn’t be completed. (Invalid attachment token)" UserInfo=0x7b68e740 {error=Invalid attachment token, GTLStructuredError=GTLErrorObject 0x7b6876e0: {message:"Invalid attachment token" code:400 data:[1]}, NSLocalizedFailureReason=(Invalid attachment token)}

推荐答案

您将ID混在一起了.

GTLQueryGmail *query2 = [GTLQueryGmail queryForUsersMessagesAttachmentsGet];
        query2.id=attachmentId;
        query2.messageId=mailID;

您从响应中获得的数据为采用Base64编码,并且已通过以下方式使URL安全

The data you get in your response is Base64-encoded and has been made URL safe by replacing all "+" with "-", and all "/" with "_".

只需将其转换回常规Base64数据并对其进行解码!在开发人员工具中尝试执行此操作(按F12键):

Simply convert it back to regular Base64-data and decode it! Try this in your Developer Tools (press F12):

atob("SGV5IE5pbGVzaCEgSSBob3BlIHlvdSB3aWxsIGdldCBpdCB0byB3b3JrIHNvb24h".replace(/\-/g, '+').replace(/\_/g, '/'));

在代码中执行相同的步骤,您将获得原始格式的数据.

Do the same steps in your code and you will have your data in its original format.

这篇关于iOS-使用messageId和attachmentId从Gmail下载附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆