user3093592
user3093592

Reputation: 37

Show JSON values in textview with Objective C iOS App

I'm new to Objective C but I'm trying to get my JSON data to show in my textview that I declared. (The textview is called textview) Here is my JSON data that is being sent from the PHP page:

{
  "userName": "derekshull",
  "userBio": "This is derekshulls bio",
  "userSubmitted": "15"
}

And here is my Objective C code that is requesting the PHP url and getting the JSON code:

NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json.php"];

NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];

id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];

NSArray *jsonArray = (NSArray *)myJSON;

for (id element in jsonArray) {
    textview.text = [NSLog(@"Element: %@", [element description])];            
}

The JSON is loading in the debug bank. I have searched and searched for 3 days through stackoverflow and the internet and this is what I've come up with, but I don't understand why it's not printing to textview.

Upvotes: 1

Views: 790

Answers (2)

Pawan Rai
Pawan Rai

Reputation: 3444

NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json.php"];

NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];

NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];

if(!error)
{

  for (id element in jsonArray) {
     textview.text = [NSString stringWithFormat:@"Element: %@",element];   
     // text view will contain last element from the loop       
 }
}
else{
  textview.text = [NSString stringWithFormat:@"Error--%@",[error description]];
 }

Upvotes: 2

Wain
Wain

Reputation: 119031

If you just want the JSON text in the text view then don't deserialize it with NSJSONSerialization, just drop the string straight in:

NSString *string = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
textview.text = string;

Upvotes: 0

Related Questions