我确信自己不熟悉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];
虽然,我仍然不清楚为什么属性没有设置。但是,看起来我至少有数据。
答案 0 :(得分:3)
创建请求操作对象不会自动启动请求。就像您在编辑中指出的那样,由您自行将其排入NSOperationQueue
或手动执行[operation start]
。
我建议您使用AFHTTPClient
与服务器进行通信,因为它提供了一种内置机制,可根据您传入的参数正确设置查询字符串或HTTP正文。请参阅Gowalla API示例客户端在示例代码中,方法AFHTTPClient -postPath:parameters:success:failure
。