iOS : Query regarding dynamically created array

标签 ios nsarray

我从 Web 服务(我的流程中的 Web 服务 2)获取四个参数 - slno、order、flag、name。我不知道这些参数会被接收多少次。在这四个参数中,我将“名称”发送到标签,因为它包含要询问的问题。

 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"some url"]];

        NSLog(@"Web service 2 url is = %@", url);

        NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
        NSLog(@"Json data = %@ \n error = %@", json, error);

        if(!error)
        {
            NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
            NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:Nil];

            //NSArray *arrayLabel = [[NSArray alloc] initWithObjects:label1, label2, label3, label4, label5, label6, nil];

            //NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:myJsonArray.count];
            i = 0;
            for(NSDictionary *myJsonDictionary in myJsonArray)
            {
                //UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
                //[label setText:myJsonDictionary[@"Name"]];

                NSString *name = myJsonDictionary[@"Name"];
                NSLog(@"Question from ws2 is %@", name);

                projectIdGobal = myJsonDictionary[@"ProjectID"];
                NSLog(@"Project id from ws2 is %@", projectIdGobal);

                slno = myJsonDictionary[@"SLNO"];
                NSLog(@"slno from ws2 is %@", slno);

                NSString *idWS2 = myJsonDictionary[@"ID"];
                NSLog(@"id from ws2 is %@", idWS2);

                order = myJsonDictionary[@"Order"];
                NSLog(@"order from ws2 is %@", order);

                flag = myJsonDictionary[@"Flag"];
                NSLog(@"flag from ws2 is %@", flag);

                [self putLabelsInScrollView:name];

                i++;
            }
            NSLog(@"Number of cycles in for-each = %d", i);

                [activity stopAnimating];
        }

- (void) putLabelsInScrollView:(NSString *)labelText
{

            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
            [label setFont:[UIFont fontWithName:@"Helvetica Neue" size:12.0f]];
            label.numberOfLines = 2;
            [label setText:labelText];

            [self.scroll addSubview:label];
            yPosition_label += 90;

            UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
            text.borderStyle = UITextBorderStyleRoundedRect;
            text.textColor = [UIColor blackColor];
            text.font = [UIFont systemFontOfSize:12.0];
            text.backgroundColor = [UIColor clearColor];
            text.keyboardType = UIKeyboardTypeDefault;
            text.delegate = self;
            [self.scroll addSubview:text];
            yPosition_text += 90;
            yPosition_result = yPosition_label + yPosition_text;

        [self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
        [self.view addSubview:self.scroll];
    }

现在,我创建了一个动态创建的文本字段,并将用户输入的答案存储在数组中,如下所示。

- (IBAction)save:(id)sender {
    NSMutableArray *mutableTextArray = [[NSMutableArray alloc] init];
    for(UITextField *field in self.scroll.subviews)
    {
        if([field isKindOfClass:[UITextField class]])
        {
            if([[field text] length] > 0)
            {
                [mutableTextArray addObject:field.text];
                //NSLog(@"Save button 1 : %@", mutableTextArray);
                //NSString *str = [str stringByAppendingString:[mutableTextArray objectAtIndex:0]];
                //[self fetchStrings:mutableTextArray];
            }
        }
    }

    NSLog(@"Save button 2 : %@", mutableTextArray);
    [self fetchStrings:mutableTextArray];
}

现在,在将答案发布到另一个 Web 服务(我的流程中的 Web 服务 3)时,我必须将从 Web 服务 2 获得的 slno、订单、标志以及用户在动态创建的字段中输入的“答案”传递给‘答案’键。我该如何获取这 4 个参数 [slno、order、flag(来自 Web 服务 2)和答案(来自动态文本字段)] 并将其发布到 Web 服务 3?

- (void) fetchStrings:(NSArray *)textArray
{
    NSLog(@"Array string = %@", textArray); //I get the array that the user enters in the dynamically created text field here

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    NSUserDefaults *getDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uidObject = [getDefaults objectForKey:@"UIDKEY"];


    NSString *str = [NSString stringWithFormat:@"{\"ProjID\": \"%@\",\"Uid\": \"%@\",\"EmailID\": \"%@\",", projectIdGobal, uidObject, emailFromLogin];
    str = [str stringByAppendingString:@"\"ProjectInviterFQAnswers\": ["];

    **for (SaveAsking *saveAsk in textArray) {
        str = [str stringByAppendingString:[NSString stringWithFormat:@"{\"slno\":\"%@\",\"Answer\": \"%@\",\"order\": \"%@\", \"flag\": \"%@\"},", saveAsk.slno, saveAsk.answer, saveAsk.order, saveAsk.flag]]; // I want to save the parameters here
    }**

// SaveAsking is a nsobject class where I have used a self created delegate for slno answer order and flag
    str = [str stringByAppendingString:@"]}"];
    NSLog(@"String is === %@", str);


    NSURL *url = [NSURL URLWithString:@"some url"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
        if(error || !data)
        {
            NSLog(@"JSON Data not posted!");
            [activity stopAnimating];
            UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Data not saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertMessage show];
        }
        else
        {
            [activity startAnimating];
            NSLog(@"JSON data posted! :)");
            NSError *error = Nil;
            NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"Response is %@", jsonObject);
        }
    }];

}

如果您了解我想要实现的目标,请纠正我的流程。左侧框中的迭代次数 == 右侧框中的迭代次数,结果位于中间框中,需要发布到 Web 服务。

enter image description here

最佳答案

尝试保留请求的字典,其中键是动态创建的 UITextField,值是另一个包含您需要发送的值的字典。

因此,当您创建文本字段时,将其添加到 subview 后,使用您的值(sino、order、flag)创建字典,并将该字典设置为文本字段。

当您准备好发送数据时,您将在 textField 和 webservice3 的值之间建立直接连接。

关于iOS : Query regarding dynamically created array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19902104/

相关文章:

ios - 如何使用 CAShapeLayer 创建圆角

ios - 使用 mapkit 信息按钮推送到第二个 View Controller

iphone - Objective-C : Handling references to object deleted from in NSMutableArray

ios - VIPER 中 UITableView 委托(delegate)和数据源的实现

ios - 有没有办法在解析服务器上安排推送通知?

ios - 嵌套函数上的两个循环导致索引超出范围

ios - 在 Swift 中使用引用设置 NSArray 实例

ios - 在 Objective-C 中使用 NSPredicate 过滤自定义数据类的数组

ios - 如何从子数组对象中检索属性值?

ios - 调用 JSON 后 NSRangeException 越界