0

我确信我对 iOS 编程很陌生,但是,我遇到了 AFNetworking 的问题。具体来说,当我使用它时,什么也没有发生。我没有从服务器得到任何响应,但是,我也没有收到任何错误。所有属性最终都为 NULL。

这是我的要求:

NSMutableDictionary *requestArray = [NSMutableDictionary new];
[requestArray setObject: @"getBio"
                 forKey: @"action"];
[requestArray setObject: @"1"
                 forKey: @"bioID"];

NSError * error = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestArray options:0 error:&error];

NSString *myRequestString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: @"http://localhost/LP/JSON/Secure/bio.php" ] ]; 

[ request setHTTPMethod: @"POST" ];
[ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[ request setHTTPBody: [myRequestString dataUsingEncoding:NSUTF8StringEncoding]];

如果我只是将请求传递给 UIWebView 或者如果我使用它,这似乎可以工作,因为我得到了我的预期结果:

NSURLResponse *response;
NSError *err;
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"responseData: %@", content);

也就是说,POST 成功,返回 JSON。

但是,这些都没有做任何事情(没有错误,没有响应):

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"Data: %@ %@", [JSON valueForKeyPath:@"firstName"], [JSON valueForKeyPath:@"lastName"]);
} failure:nil];

甚至裸露的骨头也没有尝试工作:

AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];

显然,我做错了可怕的事情。但是,无声的失败使这很难弄清楚。

谢谢你的帮助。

编辑:

没关系..我很密集。

没有创建 NSOperationQueue。

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];

虽然,我仍然不清楚为什么没有设置属性。但是,看起来我至少有数据。

4

1 回答 1

3

创建请求操作对象不会自动启动请求。就像您在编辑中指出的那样,您可以将其排入队列NSOperationQueue[operation start]手动执行。

我建议您使用 与您的服务器进行通信AFHTTPClient,因为它提供了一种内置机制,可以根据您传入的参数正确设置查询字符串或 HTTP 正文。请参阅示例代码中的 Gowalla API 示例客户端和方法AFHTTPClient -postPath:parameters:success:failure.

于 2012-01-16T06:34:17.913 回答