AlotJai AlotJai - 3 years ago 91
MySQL Question

Display GET data from PHP MySQL in Xcode 8 (Objective-c)

I managed to get the data "data1" and "data2" from PHP MySQL database.

Output :

[{"d1":"data1","d2":"data2"}]


And my question is how to display it in view controller screen?

I named the label with myLabel1 and myLabel2

viewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myLabel1,myLabel2;

- (void)viewDidLoad {
[super viewDidLoad];

NSError *error;
NSString *url_string = [NSString stringWithFormat: @"https://localhost/label.php"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"Output : %@", json);

}

Answer Source

From your JSON response format, its clear that your data hierarchy will be array -> dictionary -> key,values.

So first you will have to get array as:

NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

which you have already done well.

The next step is to dive into dictionary.

So get your first dictionary as

NSDictionary *dict = [json firstObject];

This dictionary will have your key value pairs which you will need to access. So het them like this:

NSString *data1 = [dict valueForKey:@"d1"];
NSString *data2 = [dict valueForKey:@"d2"];

Now finally set these values to your text:

myLabel1.text = data1;
myLabel2.text = data2;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download