Gerhard Teschl
Gerhard Teschl

Reputation: 59

Again: Easy way to request JSON with posting data

I´m really new to Xcode and Objective-C ... I receive an JSON-Array to show the contents in my TableView:

in my -viewDidLoad:

[super viewDidLoad];
self.navigationItem.title = @"Kategorien";
NSURL *url = [NSURL URLWithString:@"http://www.visualstudio-teschl.at/apptest/kats.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];   
if(jsonData != nil)
{
    NSError *error = nil;
    _kategorien = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
}

and in my cellForRowAtIndexPath: method:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault    reuseIdentifier:CellIdentifier];
}
NSDictionary *data = [self.kategorien objectAtIndex:indexPath.row];
cell.textLabel.text = [data objectForKey:@"KAT_NAME"];

return cell;

It works great and shows my Strings (key -> KAT_NAME) in my Table.

But: How can i send a String with my request? For example i want to send "searchnumber = 2" with my request, like an ajax-request with javascript/jquery?

I searched but only could find examples that are to difficult (and maybe to oversized?) for my needs... is there no easy way like my request and ad something like "sendWithData" or is this method completely different with my simple request?

Upvotes: 2

Views: 877

Answers (1)

lassej
lassej

Reputation: 6494

If you want to POST data, you'll need to create a NSMutableURLRequest object. You shouldn't use [NSData dataWithContentsOfURL:] anyway as this creates a synchronous request and blocks the UI. Even though it's a little more code, this is the right way to do it:

NSURL *url = [NSURL URLWithString:@"http://www.visualstudio-teschl.at/apptest/kats.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"searchnumber=2" dataUsingEncoding: NSASCIIStringEncoding];
[NSURLConnection sendAsynchronousRequest: request
                                   queue: [NSOperationQueue mainQueue]
                       completionHandler:
  ^(NSURLResponse *r, NSData *data, NSError *error) {
    // do something with data
}];

Upvotes: 4

Related Questions