Search code examples
iosjsongoogle-calendar-apinsurlrequest

Sending a NSMutableURLRequest request with “Body Requests” In iOS


I'm currently working with Google calendar API and allowing users to post event with attendees, however now I'm supposed to send a POST method that includes a "Request Body".

Here's the Request that I'm supposed to send :

https://www.googleapis.com/calendar/v3/calendars/<MyCalendorID>/events/<MyEventID>

Request Body :

{
 "end": {
  "date": "2015-05-19"
 },
 "start": {
  "date": "2015-05-20"
 },
 "attendees": [
  {
   "email": "nai.bhavesh782@gmail.com"
  }
 ]
}

I'm positive that I'm doing something wrong in [request setHTTPBody] but that's the only thing that I could think about.

Please help


Solution

  •             NSMutableDictionary *RequestDict = [[NSMutableDictionary alloc] init];
    
                BOOL *remind_bool = false;
                NSMutableDictionary *remindDict = [[[NSMutableDictionary alloc]init] autorelease];
                [remindDict setObject:[NSNumber numberWithBool:remind_bool] forKey:@"useDefault"];
    
                [RequestDict setObject:[eventInfoDict objectForKey:@"end"] forKey:@"end"];
                [RequestDict setObject:[eventInfoDict objectForKey:@"start"] forKey:@"start"];
                [RequestDict setObject:AttendeesArr forKey:@"attendees"];
                [RequestDict setObject:_txt_eventname.text forKey:@"summary"];
                [RequestDict setObject:_txt_desc.text forKey:@"description"];
                [RequestDict setObject:_txt_location.text forKey:@"location"];
                [RequestDict setObject:remindDict forKey:@"reminders"];
                [RequestDict setObject:@"tentative" forKey:@"status"];
    
                [RequestDict retain];
    
                NSLog(@"%@",RequestDict);
    
    -(void)callAPIfortesting:(NSString *)apiURL withHttpMethod:(HTTP_Method)httpMethod
          postParameterNames:(NSArray *)params
         postParameterValues:(NSArray *)values postParameterDict:(NSDictionary *)RequestDict
    {
        // Check if the httpMethod value is valid.
        // If not then notify for error.
        if (httpMethod != httpMethod_GET && httpMethod != httpMethod_POST && httpMethod != httpMethod_DELETE && httpMethod != httpMethod_PUT) {
            [self.gOAuthDelegate errorOccuredWithShortDescription:@"Invalid HTTP Method in API call" andErrorDetails:@""];
        }
        else
        {
            // Create a string containing the API URL along with the access token.
            NSString *urlString = [NSString stringWithFormat:@"%@?access_token=%@", apiURL,[_accessTokenInfoDictionary objectForKey:@"access_token"]];
            // Create a mutable request.
    
    
            NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
    
            [UserDefaults setObject:[_accessTokenInfoDictionary objectForKey:@"access_token"] forKey:@"AccessToken"];
            [UserDefaults synchronize];
    
    
    
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
            // Depending on the httpMethod value set the respective property of the request object.
            switch (httpMethod)
            {
                case httpMethod_GET:
                    [request setHTTPMethod:@"GET"];
                    break;
                case httpMethod_POST:
                    [request setHTTPMethod:@"POST"];
                    break;
                case httpMethod_DELETE:
                    [request setHTTPMethod:@"DELETE"];
                    break;
                case httpMethod_PUT:
                    [request setHTTPMethod:@"PUT"];
                    break;
    
                default:
                    break;
            }
    
            // In case of POST httpMethod value, set the parameters and any other necessary properties.
            if (httpMethod == httpMethod_POST)
            {
                // A string with the POST parameters should be built.
                // Create an empty string.
                NSString *postParams = @"";
                // Iterrate through all parameters and append every POST parameter to the postParams string.
                for (int i=0; i<[params count]; i++) {
                    postParams = [postParams stringByAppendingString:[NSString stringWithFormat:@"%@=%@",
                                                                      [params objectAtIndex:i], [values objectAtIndex:i]]];
    
                    // If the current parameter is not the last one then add the "&" symbol to separate post parameters.
                    if (i < [params count] - 1) {
                        postParams = [postParams stringByAppendingString:@"&"];
                    }
                }
    
    
                NSLog(@"%@",postParams);
    
            }
    
    
            if([NSJSONSerialization isValidJSONObject:RequestDict])
            {
                // Convert the JSON object to NSData
                NSData * httpBodyData = [NSJSONSerialization dataWithJSONObject:RequestDict options:0 error:nil];
                // set the http body
                [request setHTTPBody:httpBodyData];
            }
    
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
            NSLog(@"%@",request);
    
            // Make the request.
            [self makeRequest:request];
        }
    }