我需要从Parse API查询一些数据。下面的代码是Parse的CURL示例:
curl -X GET \
-H "X-Parse-Application-Id: XXXXX" \
-H "X-Parse-REST-API-Key: XXXXX" \
-G \
--data-urlencode 'where={"key1":"value1","key2":"value2"}' \
https://api.parse.com/1/classes/ClassName
然后,这是我的代码:
NSDictionary *dictionary = @{@"key1": @"value1", @"key1": @"value2"};
NSError *error = nil;
NSString *jsonString = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
NSURL *url = [NSURL URLWithString:fullUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-Application-Id"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSLog(@"Data: %@", data);
NSLog(@"Response: %@", response);
}else{
NSLog(@"Error: %@", error);
}
}];
[task resume];
执行后,我遇到了一些错误:
2015-01-16 18:19:57.532 ParseTest[37964:1018046]
Error: Error Domain=NSURLErrorDomain Code=-1002
"The operation couldn’t be completed. (NSURLErrorDomain error -1002.)"
UserInfo=0x7d17d320 {NSUnderlyingError=0x7d051f70 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1002.)"}
完成过去的CURL代码的Objective-C等价物是什么?或者你的建议是什么?
提前致谢。
答案 0 :(得分:1)
您需要使用PFQuery
。有关信息,请参阅Parse's iOS/OS X Documentation。
这是一些用于执行上述尝试的示例代码。它应该是该cURL代码的直接替代品:
- (void)runQuery {
PFQuery *query = [PFQuery queryWithClassName:@"ClassName"];
[query whereKey:@"key1" equalTo:value1];
[query whereKey:@"key2" equalTo:value2];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error != nil) {
// Do error handling here
} else {
// You have a valid query result
}
}
];
}
请不要忘记,您需要在应用中初始化Parse连接,然后才能拨打电话。这样,您就不需要像在cURL代码中那样传递每个请求的密钥。您可以在AppDelegate
对象的-didFinishLaunchingWithOptions:
方法中执行此操作,如下所示:
#import <Parse/Parse.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize Parse.
[Parse
setApplicationId:@"<App Id>"
clientKey:@"<Client Key>"];
}
答案 1 :(得分:1)
NSURLErrorDomain error -1002
表示不支持该网址。我的猜测是你需要对json的where
参数进行URL编码。也许改变你的URL:
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
如果这不起作用,您是否尝试过登录fullUrl
并尝试cURL
它?