Charles Vincent
Charles Vincent

Reputation: 229

Populate an array with the contents of a string object

I have a string that gets it contents from a URL. Im trying to put these contents into an array that will populate a table view. Here is the code I have. What am I doing wrong here? Thanks in advance.

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *strURL = [NSString stringWithFormat:@"http://10.247.245.87/index.php"];

    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];

    NSArray *nameArray = [[NSArray alloc]initWithContentsOfURL:<#(NSURL *)#>;

    return nameArray.count;

}

Upvotes: 0

Views: 139

Answers (3)

Sparq
Sparq

Reputation: 823

I believe there are several ways to do this, but here's a simple way to parse JSON results into arrays. Download the SBJSON framework from here and add it to your project. Then import the JSON.h file to your #import "JSON.h". After which you can parse the string into an array using this line of code nameArray = [responseString JSONValue];.

  1. Get SBJSON from here.
  2. Add SBJSON to your project and Import JSON.h like so #import "JSON.h"
  3. Parse to array like so nameArray = [responseString JSONValue];

Happy Coding!

EDIT: you can try do something like this to check to see if you have an array of Strings after you parse the JSON into an array:

for (NSString* myString in nameArray){
NSLog(@"%@",myString);
}

if the above works out then you can get the strings from the array and fill the tableview in the cellForRowAtIndexPath delegate like so:

cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];

Upvotes: 1

AppleDelegate
AppleDelegate

Reputation: 4249

use this after NSData..

NSArray *array =   [NSJSONSerialization JSONObjectWithData:dataURL options:NSJSONReadingAllowFragments error:nil];

return array;

Upvotes: 0

edzio27
edzio27

Reputation: 4140

In this line:

return nameArray.count;

you will always get 0 because you dont wait for response from serwer.

Upvotes: 0

Related Questions