2012-05-29 128 views
3

此问题可能与AFNetworking没有特别关系,但更多的是构建NSURLRequest。 我想发出使用AFNetworking-将cURL请求(使用--data-urlencode)转换为AFNetworking GET请求

curl -X GET \ 
    -H "X-Parse-Application-Id: Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J" \ 
    -H "X-Parse-REST-API-Key: iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL" \ 
    -G \ 
    --data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' \ 
    https://api.parse.com/1/classes/GameScore 

这是从parse.com API https://parse.com/docs/rest#queries-constraints下降GET请求。此请求

然而,我无法弄清楚如何写

[AFHTTPClient的getPath:参数:成功:失败。 where子句看起来不像字典,但是此函数仅为其参数输入输入字典。

+0

Day9把我带到这里! – dgrandes

回答

6

该参数需要一个NSDictionary,它将被转换为URL中的键/值对。所以,关键是容易的,但你必须先在字典中设置它之前将它转换成JSON值...

NSDictionary *jsonDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: 
           @"Sean Plott", @"playerName", 
           [NSNumber numberWithBool:NO], @"cheatMode", nil]; 

NSError *error = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error]; 

if (!jsonData) { 
    NSLog(@"NSJSONSerialization failed %@", error); 
} 

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

NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys: 
          json, @"where", nil]; 

如果我们假设您的客户端配置是这样的(通常你继承AFHTTPClient并且可以移动这些东西里面

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.parse.com/"]]; 
[client setDefaultHeader:@"X-Parse-Application-Id" value:@"Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J"]; 
[client setDefaultHeader:@"X-Parse-REST-API-Key" value:@"iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL"]; 
[client registerHTTPOperationClass:[AFJSONRequestOperation class]]; 

那么你应该能够调用

[client getPath:@"1/classes/GameScore" 
    parameters:parameters 
     success:^(AFHTTPRequestOperation *operation, id responseObject) { 
      NSLog(@"Success %@", responseObject); 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"Failed %@", error); 
     }]; 
+0

这完美。非常感谢! – Devang