Search code examples
iosobjective-chttp-postnsurlconnectionurl-parameters

Three parameter in Post method using nsurlconnection


I am new to IOS i need to pass three parameter in POST method.my parameter are (1)str (2)str1 (3)str2.this three parameter are fetch from different url in string format.

coding for POST method: i need to add these parameter in method?i already added str parameter but i am struggling to pass other two(str1,str2) parameter.

-(void) sendDataToServer : (NSString *) method params:(NSString *)str{

    NSString *post = [NSString stringWithFormat:@"branch_id=%@",str];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];


    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

    if( theConnection ){

        mutableData = [[NSMutableData alloc]init];
    }
}

Viewdidload: here also i want to str1 and str2 parameter.

[self sendDataToServer :@"POST" params:str];

Solution

  • you can implement in multiple ways

    Choice-1

    -(void) sendDataToServer : (NSString *) method firstparams:(NSString *)firststr secondparam:(NSString *)secondstr thirdparam:(NSString *)thirdstr{
    
     NSString *post = [NSString stringWithFormat:@"branch_id=%@&xxxx=%@&yyyyy=%@",firststr,secondstr,thirdstr];
    
    // continue your works as its same flow
    

    call method like

    [self sendDataToServer :@"POST" firstparams:@"yourbranchID" secondparam:@"xxxValue" thirdparam:@"yyyyvalue"];
    

    Choice-2

    what ever you did is correct, just modify some code in viewdidload or else

      // add all values in one string using  stringWithFormat
      NSString *str = [NSString stringWithFormat:@"branch_id=%@&xxxx=%@&yyyyy=%@",firststr,secondstr,thirdstr];
    // and pass the param to web call
    [self sendDataToServer :@"POST" params:str];
    

    call method as

    -(void) sendDataToServer : (NSString *) method params:(NSString *)str{
    // no need of this line
    // NSString *post = [NSString stringWithFormat:@"branch_id=%@",str];
    
    // directly called the str in her
    NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];
    
     /.... as its is continue the same work