Parse.com and AFNetworking 2.0. Date Requests

I am trying to use AFNetworking 2.0 to get entries from the Parse.com backend. I want the records to be updated after a certain date. The Parse.com documentation states that matching requests with a date field must be encoded in the format:

'where={"createdAt":{"$gte":{"__type":"Date","iso":"2011-08-21T18:02:52.249Z"}}}'

This works fine using curl.

In my application, I use AFNetworking 2.0 to run the request, as shown below. First, I installed the request and response serializer when initializing the shared client:

+ (CSC_ParseClient *)sharedClient {
static CSC_ParseClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    NSURL *baseURL = [NSURL URLWithString:@"https://api.parse.com"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    [config setHTTPAdditionalHeaders:@{ @"Accept":@"application/json",
                                        @"Content-type":@"application/json",
                                        @"X-Parse-Application-Id":@"my app ID",
                                        @"X-Parse-REST-API-Key":@"my api key"}];


    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024
                                                      diskCapacity:50 * 1024 * 1024
                                                          diskPath:nil];

    [config setURLCache:cache];

    _sharedClient = [[CSC_ParseClient alloc] initWithBaseURL:baseURL
                                     sessionConfiguration:config];
    _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
    _sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
});

return _sharedClient;

}

- (NSURLSessionDataTask *)eventsForSalesMeetingID:(NSString *)meetingID sinceDate:(NSDate *)lastUpdate completion:( void (^)(NSArray *results, NSError *error) )completion {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *dateString =  [dateFormatter stringFromDate:lastUpdate];
NSLog(@"date = %@", dateString);

NSDictionary *params = @{@"where": @{@"updatedAt": @{@"$gte": @{@"__type":@"Date", @"iso": dateString}}}};

NSURLSessionDataTask *task = [self GET:@"/1/classes/SalesMeetingEvents"
                            parameters:params
                               success:^(NSURLSessionDataTask *task, id responseObject) {
                                   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
                                   NSLog(@"Response = %@", httpResponse);
                                   if (httpResponse.statusCode == 200) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           completion(responseObject[@"results"], nil);
                                       });
                                   } else {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           completion(nil, nil);
                                       });
                                       NSLog(@"Received: %@", responseObject);
                                       NSLog(@"Received HTTP %d", httpResponse.statusCode);
                                   }

                               } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       completion(nil, error);
                                   });
                               }];
return task;

}

But this gives a 400 error from the server. The URL encoded query string looks like this after decoding:

where[updatedAt][$gte][__type]=Date&where[updatedAt][$gte][iso]=2014-01-07T23:56:29.274Z

I tried hard-coding the back end of the query string as follows:

    NSString *dateQueryString = [NSString stringWithFormat:@"{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}", dateString];


NSDictionary *params = @{@"where":@{@"updatedAt":dateQueryString}};

, 400 ; :

where[updatedAt]={"$gte":{"__type":"Date","iso":"2014-01-07T23:56:29.274Z"}}

AFNetworking? ParseSDK, , SDK - (30+ ).

+4
1

parse.com REST :

where JSON. , URL-, JSON, URL

, URL- . :

NSString *dateQueryString = [NSString stringWithFormat:@"{\"updatedAt\":{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}", dateString];
NSDictionary *parameters = @{@"where": dateQueryString};

NSDictionary dateQueryString:

NSString *dateQueryString;
NSDictionary *query = @{ @"updatedAt": @{ @"$gte": @{@"__type":@"Date",@"iso":dateString}}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:query
                                                   options:nil
                                                     error:&error];
if (!jsonData) {
    NSLog(@"Error: %@", [error localizedDescription]);
}
NSString *dateQueryString = [[NSString alloc] initWithData:jsonData
                                                  encoding:NSUTF8StringEncoding];
NSDictionary *parameters = @{@"where": dateQueryString};

- AFHTTPSessionManager:

@implementation ParseAPISessionManager

+ (instancetype)sharedSession {
    static ParseAPISessionManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[ParseAPISessionManager alloc] initWithBaseURL:[NSURL URLWithString:parseAPIBaseURLString]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        self.requestSerializer = [AFJSONRequestSerializer serializer];
        [self.requestSerializer setValue:parseAPIApplicationId forHTTPHeaderField:@"X-Parse-Application-Id"];
        [self.requestSerializer setValue:parseRESTAPIKey forHTTPHeaderField:@"X-Parse-REST-API-Key"];
    }

    return self;
}

:

ParseAPISessionManager *manager = [ParseAPISessionManager sharedSession];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:13];
[comps setMonth:2];
[comps setYear:2014];
[comps setHour:16];
[comps setMinute:0];

NSDate *feb13 = [[NSCalendar currentCalendar] dateFromComponents:comps];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *feb13str = [dateFormatter stringFromDate: feb13];

NSString *queryStr = [NSString stringWithFormat:@"{\"updatedAt\":{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}", feb13str];

NSDictionary *parameters = @{@"where": queryStr};

[manager GET:@"classes/TestClass" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
    NSLog(@"%@", responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

, ,

+2

All Articles