objective-c - 又是: Easy way to request JSON with posting data

标签 objective-c json nsurlconnection nsurlrequest

我对 Xcode 和 Objective-C 真的很陌生......我收到一个 JSON 数组来显示我的 TableView 中的内容:

在我的-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];
}

在我的cellForRowAtIndexPath:方法中:

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;

它工作得很好,并在我的表中显示了我的字符串(键 -> KAT_NAME)。

但是:我如何通过我的请求发送字符串?例如,我想通过我的请求发送“searchnumber = 2”,例如使用 javascript/jquery 的 ajax 请求?

我进行了搜索,但只能找到对于我的需求来说太困难(而且可能太大?)的示例...是否没有像我的请求和广告之类的简单方法,例如“sendWithData”,或者这种方法与我的完全不同简单的请求?

最佳答案

如果你想 POST 数据,你需要创建一个 NSMutableURLRequest 对象。无论如何,您都不应该使用 [NSData dataWithContentsOfURL:],因为这会创建同步请求并阻止 UI。尽管代码有点多,但这是正确的方法:

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
}];

关于objective-c - 又是: Easy way to request JSON with posting data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987052/

相关文章:

ios - Http直播: Forcing MPMoviePlayerController to pack headers in the http requests

ios - inAppPurchase 后停止 Flurry Ads,不退出应用程序

ios - 文件管理器未从旧应用程序中清除

ios - NSNotificationCenter 是 UITextView 的一部分吗?

json - Angular 7 HTTP GET 发送 JSON 对象作为参数

ios - NSURlConnection 取消导致内存泄漏

iphone - 如何获取 NSURLConnection 中的默认用户代理字符串?

objective-c - 错误 : "No identities are available for signing" Xcode 4. 3.1

android - 将 URL 数据插入 JSONArray

Java - 确定用户输入\n和按html形式按回车之间的区别