ios - 将 json 响应传递给 iOS 中的另一个 View Controller

标签 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

最佳答案

如果返回的数据是字典格式,在header.h类中声明nsdictionary,你想传数据,同样可以用array和string,现在如果你用的是storyboard,方法如下。

p>
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // 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...
        vc.dictionary  = self.dictionary.

    }
}

如果您想在点击手机时传输数据,这就是您必须要做的。

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

}

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

- (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"];

    }
}

关于ios - 将 json 响应传递给 iOS 中的另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729712/

相关文章:

ios - XCode 10 beta 4 分发失败 - [ERROR ITMS-90534]

objective-c - 改变实例 NSArray

objective-c - NSWindowController 是否应该在 windowWillClose :? 中释放自己

javascript - 使用 Microsoft Face api 其对象返回 400 图像无效或参数无效

android - 如何将选定的自定义数组列表值放置到相同的自定义数组列表中,但最多只能放置 5 个中的 3 个

objective-c - iOS - cellForRowAtIndexPath SQLite 排序数据?

ios - UISearchBar 在 Swift 中完成后如何停止 UIActivityIndi​​cator

iphone - 更新 UIButton 背景时的延迟

iphone - UITextField 验证