将json响应传递给iOS中的另一个视图控制器

时间:2015-11-16 06:39:39

标签: ios objective-c jsonresponse

首先我只是使用GET方法将数据发送到服务器,我收到如下的响应

2015-11-16 14:21:42.168 smartschool[1963:348015] Item actcode: ZQRTNN68
2015-11-16 14:21:42.169 smartschool[1963:348015] Item parentid: 8

如何将激活码显示到下一个viewController的标签。

这是我的代码:

#import "RegistrationViewController.h"


@interface RegistrationViewController ()

@end

@implementation RegistrationViewController
{

    NSMutableData *mutableData;

#define URL @"http://192.168.1.166/bustracking/activation/requestActivationCode"
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(IBAction)sendDataUsingGet:(id)sender{

    [self sendDataToServer : @"GET"];


}

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

    NSString *parentName  = parent_name.text;
    NSString *contactNumber = contact_number.text;
    NSString *beaconid = @"145801000095";
    //NSString *beaconMacAdd = @"14:58:01:00:00:95";

    if(parentName.length > 0 && contactNumber.length > 0){

        NSLog (@"Getting response from server...");

        NSMutableURLRequest *request = nil;

        // Only Difference between POST and GET is only in the way they send parameters

        if([method isEqualToString:@"GET"]){

            NSString *getURL = [NSString stringWithFormat:@"%@?parent_name=%@&contact_number=%@&beacon_id=%@", URL, parentName, contactNumber, beaconid];
            //url = [NSURL URLWithString: getURL];
            getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url =  [NSURL URLWithString: getURL];
            request = [NSMutableURLRequest requestWithURL:url];

            NSLog(@"urlinfo: %@", url);
            NSLog(@"link: %@", getURL);
        }

        [request setHTTPMethod:method];
        [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

        NSLog(@"connection: %@", connection);

        if( connection )
        {
            mutableData = [NSMutableData new];
        }
        else
        {
            NSLog (@"NO_CONNECTION");
            return;
        }
    }
    else
    {
        NSLog(@"NO_VALUES");
    }

}

#pragma mark NSURLConnection delegates

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    [mutableData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mutableData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog (@"NO_CONNECTION");
    return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error = nil;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:mutableData options:kNilOptions error:&error];
    NSArray *fetchedArr = [json objectForKey:@"response"];
    NSString *responseActCode;

    for (NSDictionary *user in fetchedArr)
    {
        responseActCode = [user objectForKey:@"activation_code"];
        NSLog(@"Item actcode: %@", responseActCode);
        NSLog(@"Item parentid: %@", [user objectForKey:@"parent_id"]);
        //NSLog(@"Item actcode: %@", [user objectForKey:@"activation_code"]);
    }

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:responseActCode forKey:@"HighScore"];
    [defaults synchronize];
    NSLog(@"from data: %@", [defaults objectForKey:@"HighScore"]);


    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Activation Code"
                          message:(@"%@", responseActCode)
                          delegate:nil //or self
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];

    [alert show];
}

@end

2 个答案:

答案 0 :(得分:1)

在视图控制器之间传递数据的方法有很多种。这是一个例子: 在“SomeViewController”类中创建一个公共属性(例如:responseActCodeString)并将该属性设置为激活码(例如:responseActCode)。

SomeViewController *someViewController = [[SomeViewController alloc] initWithNib:@"SomeViewController " bundle:nil];
someViewController.responseActCodeString = responseActCode;
[self pushViewController:someViewController animated:YES];

您还可以使用通知,用户默认值作为替代方案。 另请查看此link

对于故事板,在初始视图控制器中添加以下方法:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"someIdentifier"]){
        SomeViewController*someViewController= (SomeViewController*)segue.destinationViewController;
        someViewController.responseActCodeString = responseActCode;
    }
}

答案 1 :(得分:1)

如果返回的数据是字典格式,请在您要传输数据的header.h类中声明nsdictionary,类似地,您可以使用数组和字符串,现在如果您使用的是故事板,则下面是方法。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"YOUR_SEGUE_NAME_HERE"" sender:self];

}

并且您希望在单元格点击时传输数据,这就是您必须要做的事情。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{


    NSIndexPath *indexPath= [self.tableView indexPathForSelectedRow];


    // Make sure your segue name in storyboard is the same as this line

    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller

        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
now this time its array.
        vc.array= [array[indexpath.row] valueforkey@"jsonkey"];

    }
}

当调用“performSegueWithIdentifier”时,此方法自动重定向到“prepareForSegue”方法:

Activity