在Objective-C中对Parse API发出GET请求

时间:2014-09-18 05:23:03

标签: ios objective-c parse-platform

curl -X GET  -H "X-Parse-Application-Id: XYZ"   -H "X-Parse-REST-API-Key: XYZ" -G  --data-urlencode 'where={"col1":"val1", "col2":"val2"}' https://api.parse.com/1/classes/ClassName/

我尝试将上面的curl命令转换为Objective-C中的以下代码,但无济于事。任何帮助表示赞赏。

responseData = [NSMutableData data];
NSString* classURL = @"https://api.parse.com/1/classes/ClassName/";
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSString *qryString = [NSString stringWithFormat:@"where={\"col1\":\"%@\", \"col2\":\"%@\"}", val1, val2];
[request setHTTPBody:[qryString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
                                                             delegate:self];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* resp = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(resp);

2 个答案:

答案 0 :(得分:0)

我已经制作了从解析中获取用户特定图像的方法。因此,您可以使用以下方法并根据需要进行修改。

//In below method I filtered object on objectID basis. So you have to change your filtering parameter
+(NSArray *)getObjectsWithObjectId:(NSString *)objectIdStr
{

  //Change below dictionary as per your need.
  NSDictionary *createdByDict = [[NSDictionary alloc] initWithObjectsAndKeys:objectIdStr,@"objectId",@"Pointer",@"__type",@"_User",@"className", nil];
 //In this above dict is added to create a final dict for sending as parameter for my result. So this depends upon ur parse db to change above and below dictionary.
 NSDictionary *paraDict = [[NSDictionary alloc] initWithObjectsAndKeys:createdByDict,@"createdBy", nil];


//Your dictionary would be like this one below, still check and change if needed.
//Also remove above to dictionary as they just your your reference. Might be useful for your further work in case of deeper filtering.
NSDictionary *paraDict = [[NSDictionary alloc]nitWithObjectsAndKeys:col1,val1,col2,val2, nil];

 NSError *error = nil;
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paraDict 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];

 NSString *urlStr = @"YOUR_URL";
 NSString *resultStr = [Utilities addQueryStringToUrlString:urlStr withDictionary:parameters];     //Method to collaborate urlStr with parameter and encode it as per standard. 

 NSURL *url = [NSURL URLWithString:resultStr];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 [request setHTTPMethod:@"GET"];
 [request addValue:PARSE_APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
 [request addValue:PARSE_REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];
 [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

 NSURLResponse* response;

 //Capturing server response
 NSData* data = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

 NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

 NSArray *resultArray = [responseDictionary objectForKey:@"results"];

  if([responseDictionary objectForKey:@"error"]){
    [self showAlertWithTitle:@"ERROR" message:[responseDictionary objectForKey:@"error"]];
    return nil;
  }
 return resultArray;
}

//For parameter appending into url with encoding

+(NSString*)addQueryStringToUrlString:(NSString *)urlString withDictionary:(NSDictionary *)dictionary
{
  NSMutableString *urlWithQuerystring = [[NSMutableString alloc] initWithString:urlString];

 for (id key in dictionary) {
    NSString *keyString = [key description];
    NSString *valueString = [[dictionary objectForKey:key] description];

    if ([urlWithQuerystring rangeOfString:@"?"].location == NSNotFound) {
        [urlWithQuerystring appendFormat:@"?%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    } else {
        [urlWithQuerystring appendFormat:@"&%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    }
 }
 return urlWithQuerystring;
}

+(NSString*)urlEscapeString:(NSString *)unencodedString
{
  CFStringRef originalStringRef = (__bridge_retained CFStringRef)unencodedString;
  NSString *s = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,originalStringRef, NULL, NULL,kCFStringEncodingUTF8);
  CFRelease(originalStringRef);
 return s;
}

答案 1 :(得分:0)

谢谢@ walle84。我对它进行了一段时间的研究并找出了Objective-C中的卷曲等效物。

responseData = [NSMutableData data];

NSString* qryString = [NSString stringWithFormat:@"{\"col1\":\"%@\", \"col2\":\"%@\"}",
                       val1, val2];
NSString* escapedString = [qryString
                           stringByAddingPercentEncodingWithAllowedCharacters:
                           [NSCharacterSet URLHostAllowedCharacterSet]];
NSString* classURL = [NSString  stringWithFormat: @"https://api.parse.com/1/classes/ClassName/?where=%@", escapedString];
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSError* error = [[NSError alloc] init];
NSHTTPURLResponse* responseCode = nil;
NSData* oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200)
{
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* response = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];