简体   繁体   English

iOS - 如何将数组作为参数传递给AFNetworking(Objective-C)

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

I have a php file which I want to use to process data. 我有一个php文件,我想用它来处理数据。 The php file contains a function that takes in an array as parameters. php文件包含一个接收数组作为参数的函数。

php function: php功能:

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 我正在使用AFNetworking将php代码连接到Objective-C

Objective-C code: Objective-C代码:

-(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. 但是当我运行它时,php文件中的函数无法正常运行,我收到错误。 I think it has to do with how I pass the array as parameters. 我认为这与我如何将数组作为参数传递有关。

you have to path array as paramter @{@"data": @[params]} 你必须将路径数组作为参数@ {@“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);

}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM