Search code examples
phpiosobjective-cjsonafnetworking

iOS - How to pass array to AFNetworking as parameters (Objective-C)


I have a php file which I want to use to process data. The php file contains a function that takes in an array as parameters.

php function:

func((array)$input->foos as &$foo){
  $request = mb_strtolower($foo->request);
  $found = false;
  $loopCount = 0;
  while($found === false && $loopCount < 3){
    if($request === 'single' || $request === 'corner'){
      $foo->request = $single_priority[$loopCount];
    }
    else if($request === 'double'){
      $foo->request = $double_priority[$loopCount];
    }
    else if($request === 'quad'){
      $foo->request = $quad_priority[$loopCount];
    }

    $rooms = getRooms($foo, $link, $roomcounts[$foo->request]);
    if($room = $rooms->fetch_assoc()){
      $found = true;



      if ($loopCount === 0){
        if(!$link->query("REPLACE INTO reservations VALUES('{$room['room_id']}', '{$foo->user_id}', 
            '{$foo->move_in_date}', '{$foo->move_out_date}', 'Incoming', '{$foo->date_added}')")){
            $arr = array();
            $arr['error'] = "Error: " . $link->error;
            echo json_encode($arr);
            die();
        }

        array_push($result, array('user_id' => $foo->user_id, 'room_assigned' => $room['room_id'], 'request_status' => 0));
        if(!$link->query("DELETE FROM res_waiting WHERE user_id = '{$foo->user_id}'")){
            $arr = array();
            $arr['error'] = "Error: " . $link->error;
            echo json_encode($arr);
            die();
        }
      }
      else{
        if(!$link->query("INSERT IGNORE INTO reservations VALUES('{$room['room_id']}', '{$foo->user_id}', 
            '{$foo->move_in_date}', '{$foo->move_out_date}', 'Incoming', '{$foo->date_added}')")){
            $arr = array();
            $arr['error'] = "Error: " . $link->error;
            echo json_encode($arr);
            die();
        }

        array_push($result, array('user_id' => $foo->user_id, 'room_assigned' => $room['room_id'], 'request_status' => 1));
      }
    }

    $loopCount += 1;
  }

  if (found === false){
    array_push($result, array('user_id' => $foo->user_id, 'room_assigned' => 0, 'request_status' => 2));
  }
}

I am using AFNetworking to connect to the php code to Objective-C

Objective-C code:

-(void) connectToPHP:(NSArray *)parameters
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   NSString *URLString = [[NSString alloc] initWithFormat:@"ip.address/email.php"];
    [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *jsonData = responseObject;
        NSError * error=nil;
        id reponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"JSON response: %@", [reponse objectForKey:@"response"]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(error){
            NSLog(@"%@ Error:", error);
        }
    }];
}

Function call:

NSDictionary *foo = @{
                      @"id" : @"2011011",
                      @"request" : @"single",
                      @"gender" : @"M",
                      @"username" : @"name",
                      };

NSArray *arr = [NSArray arrayWithObjects:foo, nil];

[self connectToPHP:arr];

However when I run this the function in the php file does not run correctly and I get an error. I think it has to do with how I pass the array as parameters.


Solution

  • you have to path array as paramter @{@"data": @[params]}

    NSDictionary *foo = @{
                          @"id" : @"2011011",
                          @"request" : @"single",
                          @"gender" : @"M",
                          @"username" : @"name",
                          };
    
    NSArray *arr = [NSArray arrayWithObjects:foo, nil];
    
    
    // convert your object to JSOn String
    NSError *error = nil;
    NSString *createJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:arr
                                                                                          options:NSJSONWritingPrettyPrinted
                                                                                            error:&error]
                                                 encoding:NSUTF8StringEncoding];
    
    
     NSDictionary *pardsams = @{@"data": createJSON};
    
    // finally start your request
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSLog(@"Dict %@",pardsams);
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    [manager POST:@"ip.address/email.php" parameters:pardsams success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    
    }];