【问题标题】:Again: Easy way to request JSON with posting data再次:通过发布数据请求 JSON 的简单方法
【发布时间】:2013-04-13 10:57:17
【问题描述】:

我真的是 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”这样的广告,还是这种方法与我的完全不同简单的请求?

【问题讨论】:

    标签: objective-c json nsurlconnection nsurlrequest


    【解决方案1】:

    如果你想发布数据,你需要创建一个 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
    }];
    

    【讨论】:

    • 感谢您的快速回复!今天将对其进行测试:) 这会将“搜索号”发送到我的 php 吗?我有例如: $infoNumber = $_POST['searchnumber'];
    • 好的...尝试了lassej的答案,它有效:-D但我今天的大脑有一些问题,我认为:( ... ... NSLog 为我提供了正确的数据。 .. 但我不能在 viewDidLoad 之外使用这个数组?如果我尝试使用 NSLog(@"%@",_pois); 在 vi​​ewDidLoad 之外,我的日志中没有显示任何内容?在我的 .h -> @property(非原子, strong) NSArray *pois; ...我在“用数据做某事”中添加的内容:_pois = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    • completionHandler 块在 viewDidLoad 完成后执行(因为它是异步的)。因此,在该块中,您需要将数据分配给您的实例变量:“self.kategorien = ...”,然后调用类似“[self.tableView reloadData]”的内容。
    • 唯一的事情:现在我得到了很多行......这不是一个真正的问题;)......如果我尝试“NSLog(@“numberOfRows %u”,self.pois.count) ;"在我的 numberOfRowsInSection 中,我首先得到“0”,然后第二次得到正确的数字。意思是这一步被调用了两次?
    • 是的,但这是有意的。第一次你还没有加载数据,所以表是空的。第二次是显示加载的数据。
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 2011-10-28
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多